2

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Maria628
  • 224
  • 3
  • 19
  • ...are you saving the data again at all? You don't seem to. – Tomalak May 31 '20 at 06:19
  • @Tomalak, thanks for response, i have added next piece of code to write data into JSON file again,, But i dont think that is necessary since my code is failed at pop/delete element level.. if i misunderstand your question, please clarify. – Maria628 May 31 '20 at 06:26
  • What kind of data structure do you have after reading the file? Point is, your questions has nothing to do with JSON but everything with the use of that data structure! – Ulrich Eckhardt May 31 '20 at 06:28

3 Answers3

2

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)

Gabio
  • 9,126
  • 3
  • 12
  • 32
1

Try this:

with open('test.json') as fp:
    data = json.loads(fp.read())
    del data['Codes']['8888']
deadshot
  • 8,881
  • 4
  • 20
  • 39
0

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)
Jrog
  • 1,469
  • 10
  • 29