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:

    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', ''))

Leave a Reply