Bangbangbang
Bangbangbang

Reputation: 560

How to use loops to extract elements from JSON in Python?

json_data = [{'User_Info':[{'Name':'John'},{'Name':'Ashly'}, 
{'Name':'Herbert'}]},
{'User_Info':[{'Name':''}]},
{'User_Info':[{'Name':'Lee'},{'Name':'Patrick'},{'Name':'Herbert'}]},
{'User_Info':[{'Name':'Benjamine'}]}]

I have JSON data and the length of the data is 5. I'd like to use loops to find names from that data. I've tried the code below but didn't get the expected outputs:

names_outputs = []
for ppl in json_data:
    for i in ppl['User_Info']:
        names_outputs.append(i['Name'])

print(names_outputs)
>>['John','Ashly','Herbert','Lee','Patrick','Walter','Steve','Benjamine']

However, my expected outputs should be like this:

[['John','Ashly','Herbert'],[],['Lee','Patrick','Herbert'],['Walter','Steve'],['Benjamine']]

Upvotes: 1

Views: 68

Answers (1)

Selcuk
Selcuk

Reputation: 59297

You can use a nested list comprehension for that:

>>> [[name["Name"] for name in people] for people in  [d["User_Info"] for d in json_data]]
[['John', 'Ashly', 'Herbert'], [''], ['Lee', 'Patrick', 'Herbert'], ['Benjamine']]

If you want to eliminate empty strings, use filter:

>>> [filter(None, [name["Name"] for name in people]) for people in  [d["User_Info"] for d in json_data]]
[['John', 'Ashly', 'Herbert'], [], ['Lee', 'Patrick', 'Herbert'], ['Benjamine']]

Upvotes: 1

Related Questions