0

I try to write script for deleting JSON fragment. Currently I stopped with deleting key and value. I get key error 0:

File "<stdin>", line 4, in <module>
KeyError: 0

I use json module and Python 2.7.

My sample json file is this:

"1": {
    "aaa": "234235",
    "bbb": "sfd",
    "date": "01.01.2022",
    "ccc": "456",
    "ddd": "dghgdehs"
},
"2": {
    "aaa": "544634436",
    "bbb": "rgdfhfdsh",
    "date": "01.01.2022",
    "ccc": "etw",
    "ddd": "sgedsry"
}

And faulty code is this:

import json

obj  = json.load(open("aaa.json"))

for i in xrange(len(obj)):
    if obj[i]["date"] == "01.01.2022":
        obj.pop(i)
        break

What I do wrong here?

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

1

i will take on the integer values 0, 1, but your object is a dictionary with string keys "1", "2". So iterate over the keys instead, which is simply done like this:

for i in obj:
    if obj[i]["date"] == "01.01.2022":
        obj.pop(i)
        break
Thomas
  • 174,939
  • 50
  • 355
  • 478
0

The way you're reading it in, obj is a dict. You're trying to access it as a list, with integer indices. This code:

for i in range(len(obj)):
    if obj[i]["date"] == "Your Date":
        ...

First calls obj[0]["date"], then obj[1]["date"], and so on. Since obj is not a list, 0 here is interpreted here as a key - and since obj doesn't have a key 0, you get a KeyError.

A better way to do this would be to iterate through the dict by keys and values:

for k, v in obj.items():
    if v["date"] == "your date":  # index using the value
        obj.pop(k)                # delete the key
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Changing the object you are iterating-over doesn't work. There are ways to accomplish the same thing however — see [my answer](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop/4082739#4082739) to a question on the topic (which also applies to dictionaries). – martineau Feb 03 '22 at 12:06
  • Thanks! this ended with KeyError: 'date' – hurricane2923 Feb 03 '22 at 12:28
0

In your loop, range yields integers, the first being 0. The is no integer as key in your json so this immediately raises a KeyError.

Instead, loop over obj.items() which yields key-value pairs. Since some of your entries are not dict themselves, you will need to be careful with accessing obj[i]['date'].

if isinstance(v, dict) and v.get("date") == "01.01.2022":
    obj.pop(k)
    break
martineau
  • 119,623
  • 25
  • 170
  • 301