我在它與JSON數據的文件,像這樣:在Python中迭代JSON列表的問題?
{
"Results": [
{"Id": "001",
"Name": "Bob",
"Items": {
"Cars": "1",
"Books": "3",
"Phones": "1"}
},
{"Id": "002",
"Name": "Tom",
"Items": {
"Cars": "1",
"Books": "3",
"Phones": "1"}
},
{"Id": "003",
"Name": "Sally",
"Items": {
"Cars": "1",
"Books": "3",
"Phones": "1"}
}]
}
我無法弄清楚如何通過JSON正常循環。我想循環訪問數據,併爲數據集中的每個成員獲取一個帶汽車的名稱。我怎樣才能做到這一點?
import json
with open('data.json') as data_file:
data = json.load(data_file)
print data["Results"][0]["Name"] # Gives me a name for the first entry
print data["Results"][0]["Items"]["Cars"] # Gives me the number of cars for the first entry
我試圖通過他們與循環:
for i in data["Results"]:
print data["Results"][i]["Name"]
但收到一個錯誤: 類型錯誤:列表索引必須是整數,而不是字典
'爲i的數據[「結果」]:I [「名稱「]' –
如果我正確理解了你的話,你需要:'[person''Name']:person ['Items'] ['Cars'] for data in data [」Results「]}'。 – pzp