Armen Arzumanyan
Armen Arzumanyan

Reputation: 2053

Python reading JSON value, error

I have simple JSON and after for I am reading values inside it.

this is a code:

 for row in returned_data['devices']:
     print (row['version'])

script print all "version" values and in the end

Traceback (most recent call last):
  File "api.py", line 370, in <module>
    main(sys.argv[1:])
  File "api.py", line 71, in main
    print (row['version'])
KeyError: 'version'

Why?

Upvotes: 0

Views: 72

Answers (1)

Igl3
Igl3

Reputation: 5108

If you need every row to contain the key version, you have a mistake in your dictionary, because the exception is indicating, that there is a row, which is missing this key.

In this case you have to check why your dictionary is wrong.

Otherwise, if only some of the rows contain version and you don't need every row to have this key, you can get around the error by using .get() function like this:

for row in returned_data['devices']:
    print (row.get('version'))

This prints the version for every row, containing the key and None for the ones without version.

Another thing you could do is using a try...except...:

for row in returned_data['devices']:
    try:
        print (row['version'])
    except KeyError:
        print ("row does not contain 'version'")

Upvotes: 2

Related Questions