简体   繁体   中英

How to pass json list values into python list?

My json data will print all the items of my emailList when I do this:

        print(data['emailList'])

and it will return this:

[
{
'emailId': 987654321,
'customerId': 123456789,
},
{
'emailId': 56789,
'customerId': 8765,
}
]

How could I include all the possible values for customerId into my final_list? I've tried this:

 final_list = []
    for each_requ in data:
        final_list.append(each_requ)[emailList][customerId]
    return final_list

but received this error:

 TypeError: list indices must be integers or slices, not str

desired output:

    [123456789 ,8765]

here the solution


your_json = [{'emailId': 987654321, 'customerId': 123456789},
 {'emailId': 56789, 'customerId': 8765}]

[i['customerId']for i in your_json]  
[123456789, 8765]

so for you code you can do something like that

email_list = data['emailList']
result = [i['customerId']for i in email_list] 

or single line

result = [i['customerId']for i in data['emailList']] 
 final_list = []
    for each_requ in data:
        final_list.append(each_requ['customerId'])
    return final_list

this should return your desired results if json like dict is in data variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM