I have a JSON file that looks like this:
{
"returnCode": 200,
"message": "OK",
“people”: [
{
“details: {
"first": “joe”,
“last”: doe,
“id”: 1234567,
},
“otheDetails”: {
“employeeNum”: “0000111222”,
“res”: “USA”,
“address”: “123 main street”,
},
“moreDetails”: {
“family”: “yes”,
“siblings”: “no”,
“home”: “USA”,
},
},
{
“details: {
"first": “jane”,
“last”: doe,
“id”: 987654321,
},
“otheDetails”: {
“employeeNum”: “222333444”,
“res”: “UK”,
“address”: “321 nottingham dr”,
},
“moreDetails”: {
“family”: “yes”,
“siblings”: “yes”,
“home”: “UK,
},
}
This shows two entries, but really there are hundreds or more. I do not know the number of entries at the time the code is run.
My goal is to iterate through each entry and get the 'id' under "details". I load the JSON into a python dict named 'data' and am able to get the first 'id' by:
data['people'][0]['details']['id']
I can then get the second 'id' by incrementing the '0' to '1'. I know I can set i = 0 and then increment i, but since I do not know the number of entries, this does not work. Is there a better way?
CodePudding user response:
Less pythonic then a list comprehension, but a simple for loop will work here.
You can first calculate the number of people in the people
list and then loop over the list, pulling out each id at each iteration:
id_list = []
for i in range(len(data['people'])):
current_id = data['people'][i]['details']['id']
id_list.append(current_id)
CodePudding user response:
You can use dict.get
method in a list comprehension to avoid getting a KeyError on id
. This way, you can fill dictionaries without id
s with None
:
ids = [dct['details'].get('id') for dct in data['people']]
If you still get KeyError, then that probably means some dct
s in data['people']
don't have details
key. In that case, it might be better to wrap this exercise in try/except
. You may also want to identify which dct
s don't have details
key, which can be gathered using error_dct
list (which you can uncomment out from below).
ids = []
#error_dct = []
for dct in data['people']:
try:
ids.append(dct['details']['id'])
except KeyError:
ids.append(None)
#error_dct.append(dct)
Output:
1234567
987654321