[英]Extract value from json data using python
執行 API 請求后,如果結果方括號下有大括號,我會得到 json 'data' 這有每個記錄在不同的集合中。
我想提取數字並存儲/打印它們,用逗號分隔。
所以要求輸出
0010041,0010042
我曾嘗試使用以下內容,但它返回以下錯誤。
TypeError: list indices must be integers or slices, not str
如果結果只有一組括號它工作正常,我是否必須將多個結果轉換為一個,然后在出現“數字”時一直提取?
import json
import sys
#load the data into an element
data={'result': [{'number': '0010041', 'day_of_week': 'monday'}, {'number': '0010042', 'day_of_week': 'tuesday'}]}
#dumps the json object into an element
json_str = json.dumps(data)
#load the json to a string
resp = json.loads(json_str)
print (resp['result'])
print (resp['result']['number'])
錯誤消息很明確:您正在嘗試訪問字典列表,但操作不正確。
將最后一行替換為:
for i in resp['result']:
print(i['number'])
更新:
正如評論中所建議的,您可以使用列表理解。 所以為了得到你想要的結果,你可以這樣做:
print(",".join([i['number'] for i in resp['result']]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.