Solving TypeError: ‘unicode’ object does not support item deletion when trying to delete values from a JSON object

TypeError: ‘unicode’ object does not support item deletion is an error which occurs when you want to remove a key but you do it the wrong way.

In the blog post I to explain why this error occurs and how you can solve it, I will also include the best solution which can help you remove this error for good.

Exploring the TypeError: ‘unicode’ object does not support item deletion

TypeError: ‘unicode’ object does not support item deletion is an error which occurs when you want to remove a key but you do it the wrong way.

The error should look like this. Double check in order to avoid mixing between errors.

                                                                       #
TypeError: 'unicode' object does not support item deletion
                                                                       #

Bellow is the solution that has worked for me and will help you to successfully solve your problem.

Solution : use del to remove the undesired key

The error happens when you want to remove a key if it is there while ensuring that the loop wont fail if the key is not there.

For example, if we want to remove the ‘labels’ key, the code bellow will cause the error.

                                                                       #
import json
with open('info.json', 'r') as info_file:    # the with context manager
    info = json.load(info_file)
for element in info:                         # for loop
    element.pop('labels', None)
with open('info.json', 'w') as info_file:    # the with context manager
    info = json.dump(info, info_file)
                                                                       #

To avoid the error, we can choose to use del, after introducing del to the code, we need to introduce other changes to the code, exactly like in the resulting code bellow.

                                                                       #
import json
with open('data.json') as data_file:
    data = json.load(data_file)
for element in data:                       # for loop
    if 'labels' in element:
        del element['labels']
with open('data.json', 'w') as data_file:  # the with context manager
    data = json.dump(data, data_file)
                                                                       #

The solution above should be enough to get rid of the error for good.

If the solutions above helped you, consider supporting us on Kofi, any help is appreciated.

Summing-up

The article is over, I hope I have been able to help you solve this error or at least guide you in the right direction, check out other solutions to different errors you can do that by using the search bar on top of this page.

Keep learning, keep coding guys, cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/