我想要列印,python 'json' 串列,字典匯入混合資料
考試json資料
{
"data": [
{
"rows": [
{
"dimensions": [
{
"value": "title1"
}
],
"metrics": [
{
"value": "potato"
},
{
"value": "sweetpotato"
},
{
"conversion_annotation_value": []
},
{
"value": "123123"
}
]
},
]
}
],
}
據我所知,我使用嘗試
itemlist = json.loads(r.text)
for i in itemlist['data']['rows']['dimensions']:
...
for i in itemlist['data']['rows']['metrics']:
...
錯誤,我看到了
TypeError: list indices must be integers or slices, not str
我想看看,這個 json 資料
'title1'
'123123'
uj5u.com熱心網友回復:
它們是每個字典中的串列。所以你需要首先像串列元素一樣訪問它們:
for i in itemlist['data'][0]['rows'][0]['dimensions']:
print(i.get('value'))
for i in itemlist['data'][0]['rows'][0]['metrics']:
print(i.get('value'))
uj5u.com熱心網友回復:
改用字典itemlist['data']['rows'].get('dimensions', [])的.get()屬性。
或者更籠統地說:
itemlist = json.loads(r.text)
for k, v in itemlist['data']['rows']:
for i in v:
if k == 'a':
# code ....
elif k == 'b':
# code ....
# ...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496484.html
