js = {
"status": "ok",
"meta": {
"count": 1
},
"data": {
"542250529": [
{
"all": {
"spotted": 438,
"battles_on_stunning_vehicles": 0,
"avg_damage_blocked": 39.4,
"capture_points": 40,
"explosion_hits": 0,
"piercings": 3519,
"xp": 376586,
"survived_battles": 136,
"dropped_capture_points": 382,
"damage_dealt": 783555,
"hits_percents": 74,
"draws": 2,
"battles": 290,
"damage_received": 330011,
"frags": 584,
"stun_number": 0,
"direct_hits_received": 1164,
"stun_assisted_damage": 0,
"hits": 4320,
"battle_avg_xp": 1299,
"wins": 202,
"losses": 86,
"piercings_received": 1004,
"no_damage_direct_hits_received": 103,
"shots": 5857,
"explosion_hits_received": 135,
"tanking_factor": 0.04
}
}
]
}
}
讓我們將這個 json 命名為“js”作為一個變數,這個變數將在一個 for 回圈中。為了更好地理解我在這里做什么,我正在嘗試從游戲中收集資料。這個游戲有數百種不同的坦克,每個坦克都有tank_id,我可以用tank_id將tank_id發布到游戲服務器并將性能資料回應為“js”。
for tank_id: json = requests.post(tank_id) etc...
并將所有這些值提取到我的資料庫中,如螢屏截圖所示。

我的python代碼:
def api_get():
for property in js['data']['542250529']['all']:
spotted = property['spotted']
battles_on_stunning_vehicles = property['battles_on_stunning_vehicles']
# etc
# ...
insert_to_db(spotted, battles_on_stunning_vehicles, etc....)
例外是:
for property in js['data']['542250529']['all']:
TypeError: list indices must be integers or slices, not str
什么時候:
print(js['data']['542250529'])
我將 js 的其余部分作為字串獲取,但我無法迭代...不能使用有效的 json 字串,js['data']['542250529'] 中的內容也是一個僅包含專案“所有”...,任何幫助將不勝感激
uj5u.com熱心網友回復:
您剛剛錯過[0]了獲取串列中的第一項:
def api_get():
for property in js['data']['542250529'][0]['all']:
spotted = property['spotted']
# ...
仔細查看源 JSON 中的資料結構。
uj5u.com熱心網友回復:
有一個包含鍵為 的字典的串列all。所以你需要使用js['data']['542250529'][0]['all']not js['data']['542250529']['all']。然后就可以使用.items()來獲取鍵值對了。
見下文。
js = {
"status": "ok",
"meta": {
"count": 1
},
"data": {
"542250529": [
{
"all": {
"spotted": 438,
"battles_on_stunning_vehicles": 0,
"avg_damage_blocked": 39.4,
"capture_points": 40,
"explosion_hits": 0,
"piercings": 3519,
"xp": 376586,
"survived_battles": 136,
"dropped_capture_points": 382,
"damage_dealt": 783555,
"hits_percents": 74,
"draws": 2,
"battles": 290,
"damage_received": 330011,
"frags": 584,
"stun_number": 0,
"direct_hits_received": 1164,
"stun_assisted_damage": 0,
"hits": 4320,
"battle_avg_xp": 1299,
"wins": 202,
"losses": 86,
"piercings_received": 1004,
"no_damage_direct_hits_received": 103,
"shots": 5857,
"explosion_hits_received": 135,
"tanking_factor": 0.04
}
}
]
}
}
for key, val in js['data']['542250529'][0]['all'].items():
print("key:", key, " val:", val)
#Or this way
for key in js['data']['542250529'][0]['all']:
print("key:", key, " val:", js['data']['542250529'][0]['all'][key])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/363328.html
