Skip to content
Advertisement

How do i delete an element of a json object with python?

I’m trying to delete elements from _notes that have _type as 1, but i keep getting an error and I’m not sure what it means, nor do I know how to fix it.. can anyone help me?

My trimmed JSON:

{
    "_notes": [
        {
            "_time": 10,
            "_lineIndex": 2,
            "_lineLayer": 0,
            "_type": 0,
            "_cutDirection": 7
        },
        {
            "_time": 12,
            "_lineIndex": 2,
            "_lineLayer": 0,
            "_type": 1,
            "_cutDirection": 1
        },
        {
            "_time": 14,
            "_lineIndex": 2,
            "_lineLayer": 1,
            "_type": 1,
            "_cutDirection": 0
        }
    ]
}

My python script:

#!/usr/bin/python3

import json
obj = json.load(open("ExpertPlusStandardd.dat"))

for i in range(len(obj["_notes"])):
    print(obj["_notes"][i]["_type"])
    if obj["_notes"][i]["_type"] == 1:
        obj.pop(obj["_notes"][i])

open("test.dat", "w").write(
    json.dumps(obj, indent=4, separators=(',', ': '))
)

Error: Traceback (most recent call last): File "C:programmingpythontrain_one_handrun.py", line 9, in <module> obj.pop(obj["_notes"][i]) TypeError: unhashable type: 'dict'

Advertisement

Answer

It is usually a bad idea to delete from a list that you’re iterating. Reverse iterating avoids some of the pitfalls, but it is much more difficult to follow code that does that, so usually you’re better off using a list comprehension or filter.

obj["_notes"] = [x for x in obj["_notes"] if x["_type"] != 1]

This gives us the expected output :

{'_notes': 
   [
       {
            '_time': 10, 
            '_lineIndex': 2, 
            '_lineLayer': 0, 
            '_type': 0, 
            '_cutDirection': 7
       }
   ]
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement