如何将json列表值传递到python列表中?
执行此操作时,我的json数据将打印电子邮件列表中的所有项目:如何将json列表值传递到python列表中?,python,json,Python,Json,执行此操作时,我的json数据将打印电子邮件列表中的所有项目: print(data['emailList']) 它将返回以下内容: [ { 'emailId': 987654321, 'customerId': 123456789, }, { 'emailId': 56789, 'customerId': 8765, } ] 如何将customerId的所有可能值都包含到最终的\u列表中?我试过这个: final_list = [] for each_requ i
print(data['emailList'])
它将返回以下内容:
[
{
'emailId': 987654321,
'customerId': 123456789,
},
{
'emailId': 56789,
'customerId': 8765,
}
]
如何将customerId的所有可能值都包含到最终的\u列表中?我试过这个:
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
期望输出:
[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']]
这里是解决办法
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']]
如果类似于json的dict位于数据变量中,则这将返回所需的结果
如果类似json的dict在data
变量中print(data['emailList'][customerId])
不会打印任何内容,那么这应该会返回您想要的结果。您的“json数据”是普通的Python类型-在您的示例中是一个Python dict,“emailList”关键点指向Python dict的Python列表。从json获取这些数据的事实与此完全无关。print(data['emailList'][customerId])
不会打印任何内容。您的“json数据”是普通的Python类型-在您的例子中是一个Python dict,“emailList”关键点指向Python dict的Python列表。瞧,你从json获取这些数据的事实是完全不相关的。