[英]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.