0

I want to be able to check if a json file has the top level key I'm looking for and delete that nested dictionary.

Json file:

{
    "One": {
        "action": "One",
        "delay": 1559243024.3665395,
        "seconds": 0,
        "score": 0,
        "delta": 1559183024.3665395,
        "grace_sec": 60000
    },
    "Two": {
        "action": "Two",
        "delay": 1559321009.969849,
        "seconds": 0,
        "score": 14,
        "delta": 1559261009.969849,
        "grace_sec": 60000
    },
    "Three": {
        "action": "Three",
        "delay": 1559909745.5981774,
        "seconds": 0,
        "score": 0,
        "delta": 1559309745.5981774,
        "grace_sec": 600000
    },
    "Four": {
        "action": "Four",
        "delay": 1559909757.0363235,
        "seconds": 0,
        "score": 1,
        "delta": 1559309757.0363235,
        "grace_sec": 600000
    }
}

This is what I have tried so for but hasn't worked:

if name == child.text:
              ...
                with open("streak.json", "r+") as f:
                    data = json.load(f)

                for x in data:
                    if name in x:
                        del x[name]

                with open("streak.json", "w") as file:
                    data = json.dump(data, file)

So for instance if the name == "Two", then all of Two's key value pairs would be deleted including Two itself.

yemi.JUMP
  • 313
  • 2
  • 12
  • So you want to delete `"Two": { "action": "Two", "delay": 1559321009.969849, "seconds": 0, "score": 14, "delta": 1559261009.969849, "grace_sec": 60000 },` ? – Devesh Kumar Singh May 31 '19 at 13:49
  • It's not Two, I want to delete but any dictionary that the program says == child.text. I was just using Two as an example. – yemi.JUMP May 31 '19 at 13:51

2 Answers2

3

You can use the pop() function. This function will delete the key from the dictionary and return the value. If the key does not exist, it will return a default value. eg:

>>> d = {'a': 1, 'b': 2}
>>> d.pop('a', None)
1
>>> d
{'b': 2}
>>> d.pop('c', None)
>>> d
{'b': 2}
>>>

This will reduce the burden of checking if a key exists or not when deleting and you won't have to rely on KeyError to check if it failed. You can check if the return value is not your sentinel value, None in this case, then the key was successfully deleted. If it is the sentinel value, then the key never existed.

prateeknischal
  • 752
  • 4
  • 12
0

Just delete the top level item:

with open("streak.json", "r") as f:
    data = json.load(f)

if name in data:
    del data[name]

with open("streak.json", "w") as file:
    json.dump(data, file)
quamrana
  • 37,849
  • 12
  • 53
  • 71