0

In this answer I understand that I can use the GET instruction to catch an element of a JSON file and get a None if this does not exists. But I can't understand how to use with more than one level of JSON data.

Let's have a look at the following example:

import json
json_input = '{"persons": [{"name": "Brian", "city": "Seattle"}, {"name": "David", "city": "Amsterdam"} ] }'
d = json.loads(json_input)
  • Input d.get('persons') output

[{'name': 'Brian', 'city': 'Seattle'}, {'name': 'David', 'city':'Amsterdam'}]

  • Input d.get('animals') output

None

but I would like to use the same to check if d['persons'][0]['name'] exist, or if d['persons'][0]['tel_number']. If I use d.get(['persons'][0]['name']) I get the following error:

Traceback (most recent call last): File "", line 1, in d.get(['persons'][0]['name']) TypeError: string indices must be integers

Nicolaesse
  • 2,554
  • 12
  • 46
  • 71

2 Answers2

1

This looks like a valid solution:

def myGet(d, k1, k2, k3):
    try:
        return d[k1][k2][k3]
    except (TypeError, IndexError, KeyError):
        return None

asdfg = myGet(d, 'persons', 0, 'name')

You got the TypeError because Python treated ['persons'] as a list containing one string, instead of an index, so ['persons'][0] gets to 'persons', which cannot be indexed by another string.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • The function you posted works but I don't find it useful. I would find useful something like myGet(d['persons'][0]['name']) that output 'Brian' and myGet(d['persons'][0]['abc']) that output 'None'. – Nicolaesse Mar 12 '18 at 20:17
  • @Nicolaesse You of course can add another parameter to the function that's used in the third index. Like I just updated the answer. – iBug Mar 13 '18 at 01:20
1

Correct approach would be this:

d.get('persons')[0].get('name')

get() applied on dictionary returns value of given key, if possible. Then we access list inside it and try to get() value of key called name again.

This can raise IndexError or KeyError exceptions if there's no list or no persons or name key, but you can handle this with try .. except block as outlined in iBug's answer.

tvm
  • 3,263
  • 27
  • 37