繁体   English   中英

如何将 json 列表值传递到 python 列表中?

[英]How to pass json list values into python list?

当我这样做时,我的 json 数据将打印我的 emailList 的所有项目:

        print(data['emailList'])

它会返回这个:

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

如何将 customerId 的所有可能值包含到我的 final_list 中? 我试过这个:

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

但收到此错误:

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

所需的 output:

    [123456789 ,8765]

这里的解决方案


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

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

所以对于你的代码,你可以做类似的事情

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

或单行

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

如果像 dict 这样的 json 在data变量中,这应该会返回您想要的结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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