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

1
  • Who downvoted my question could explain me why? Commented Mar 14, 2018 at 13:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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 You of course can add another parameter to the function that's used in the third index. Like I just updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.