【问题标题】:Iterate through nested JSON in Python在 Python 中遍历嵌套的 JSON
【发布时间】:2022-01-01 01:08:35
【问题描述】:
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 发布到游戏服务器并将性能数据响应为“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'] 里面也是一个列表仅包含项目“所有”...,任何帮助将不胜感激

【问题讨论】:

  • 542250529 包含一个列表:js['data']['542250529'][0]['all']

标签: python json iterator


【解决方案1】:

您刚刚错过了[0] 以获得列表中的第一项:

def api_get():
   for property in js['data']['542250529'][0]['all']:
       spotted = property['spotted']
# ...

仔细查看源 JSON 中的数据结构。

【讨论】:

  • @Master Schifou 这也可以。
  • 从昨天开始我就一直睡不着想发现我有多愚蠢哈哈,列表中的第一项得到0作为索引,我感谢你的努力大老板
【解决方案2】:

有一个列表包含带有all 键的字典。所以你需要使用js['data']['542250529'][0]['all'] 而不是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])

【讨论】:

  • 我刚刚找到了制作新 for 循环的解决方案,但不知道它是如何工作的。但多亏了你们,我正在以简单的方式做到这一点......
猜你喜欢
  • 2020-04-09
  • 2016-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
  • 1970-01-01
  • 2012-11-11
相关资源
最近更新 更多