Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python JSON parser not seeing a single key

Trying to make a script to iterate over some JSON coming from an API that is formatted like this:

{'disk': 0, 'pid': 1234, 'cpus': 4, 'maxdisk': 80530636800, 'diskwrite': 0, 'netout': 18664223636, 'status': 'running', 'cpu': 0.0288084074674866, 'mem': 5976839531, 'name': 'foo', 'uptime': 102152, 'diskread': 0, 'tags': 'tag1;tag2', 'maxmem': 8589934592, 'netin': 2945853297, 'vmid': 111}

The particular key I am looking to access is the "tags" key. Every other key can be accessed with this Python loop:

for i in range(len(json['data'])):
  currentVM = json['data'][i]
  print (currentVM['cpu'])

The sample JSON above is the output of currentVM at one index. However if I replace in this example ‘cpu’ with ‘tags’ I get the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    print (currentVM['tags'])
           ~~~~~~~~~^^^^^^^^
KeyError: 'tags'

They key is clearly there, and all the other keys seem to work fine. Wondering if this key being a list may change its behavior perhaps?

The current version of the script that creates the ‘currentVM’ variable was me thinking maybe going too many indexes deep was the issue, but that doesn’t seen to be the case as I am still getting the same error.

>Solution :

There must not be a tags key in every element. Use .get() so you can provide a default.

print(currentVM.get('tags', ''))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading