Scott Scott - 1 year ago 127
JSON Question

having Key Error while printing json data

python 3.5.1

hi i have following json and python code and i want to print json data but it has an error that says:

Key Error : 'A'


data = json.load(...)
for item in data['x']
print (item['A'])



whats my problem?

Answer Source

The problem is that your code assumes that every item in data['x'] will have a key 'A', but as soon as you iterate to a dict that does not have such a key you will get a KeyError.

Try using item.get('A') which will return None (or a default you provide) if there is no key 'A' in your dictionary. It seems like you want to do something like this:

data = json.load(...)
for item in data['x']:
    value = item.get('A')
    if value:

This will print the value associated with the key 'A' if it exists, otherwise it will move on to the next dictionary in the list.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download