Deleting sub-element from JSON file

Viewed 440

I thought it was simple to delete a key from JSON nested dict, but I end up with errors . I have JSON file as shown below, and want to delete a key "8888" from its element "Codes".

dummy.json:

{
    "Codes": {
        "8888": "code1|18888",
        "9999": "code2|19999",
        "7777": "code3|17777"
    },
    "Names": {
        "Site1": "Site1|18888",
        "Site2": "Site2|19999",
        "Site3": "Site3|17777"
    }
}

Python code:

import json

with open('dummy.json') as json_data:
    data = json.load(json_data)
    for element in data["Codes"]:
        #del element['8888']
        element.pop('8888', None)

with open('dummy.json'), 'w') as outfile:  
    json.dump(data, outfile)

Result:

For the first attempt, I tried del element['8888'] and it throws TypeError: 'str' object does not support item deletion

As per example found here I have tried with element.pop('8888', None) and it throws AttributeError: 'str' object has no attribute 'pop' error.

I am not sure what mistake I did, please help.

3 Answers

While iterating over data["Codes"], element will be a key of the data["Codes"] dictionary and it's a string, which doesn't have a pop function (can be applied on dicts only).

Try instead:

import json
with open('dummy.json') as json_data:
    data = json.load(json_data)
    data["Codes"].pop("8888")

with open('dummy.json', 'w') as outfile:  
    json.dump(data, outfile)

Try this:

with open('test.json') as fp:
    data = json.loads(fp.read())
    del data['Codes']['8888']

In for element in data["Codes"] loop, element will be key of data["Codes"] dictionary. So if print all element of data["Codes"], result is like this.

for element in data["Codes"]:
    print(element)
>>> 8888
>>> 9999
>>> 7777

You don't need for loop. If you want to delete(or pop) some key of data["Codes"], just do like this.

data["Codes"].pop("8888", None)
Related