gpt4 book ai didi

python - 使用多个 'for' 循环解码嵌套的 JSON

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:07 25 4
gpt4 key购买 nike

我是 Python 的新手(上周),已经达到了我的极限。在这上面花了三天时间,我大部分时间都在 stackoverflow 上,但我不知道如何继续下去!

Json有多个嵌套数组。它可以包含三个(如下面的示例 (json.txt) 所示)或 30 个。我需要遍历每个,然后深入到“innings”并最终获得“wickets”的值。这是我感到困惑的最后一步。任何人都可以建议吗?

你的绝望

import os, json,requests
print 'Starting'
url = 'https://dl.dropboxusercontent.com/u/3758695/json.txt'

# download the json string
json_string = requests.get(url)
print 'Downloaded json'

# get the content
the_data = json_string.json()
print 'the_data has length ', len(the_data)
for index in range(len(the_data)):
print 'Now working on index ', index
for wicket in the_data[index]:
print 'wicket equals ',wicket
# OK - I can see Innings. Now, how do I get inside
# and obtain 'wickets'?

最佳答案

首先,不要使用索引而是直接遍历列表;这样你就可以给他们起有意义的名字。顶层是一个条目列表,每个条目都是一个带有 'innings' 键的字典,每个 innings 都是一个字典列表,其中包括: wickets 键:

for entry in data:
for inning in entry['innings']:
print inning['wickets']

这打印:

>>> for entry in data:
... for inning in entry['innings']:
... print inning['wickets']
...
10
9
0
0

这也使得在每个级别添加信息变得更加容易:

>>> for entry in data:
... print entry['description']
... for i, inning in enumerate(entry['innings']):
... print 'Innings {}: {} wickets'.format(i + 1, inning['wickets'])
...
Rest of Sri Lanka v Sri Lanka A at Pallekele, May 14, 2013
Innings 1: 10 wickets
Innings 2: 9 wickets
63rd match: Royal Challengers Bangalore v Kings XI Punjab at Bangalore, May 14, 2013
Innings 1: 0 wickets
Innings 2: 0 wickets
64th match: Chennai Super Kings v Delhi Daredevils at Chennai, May 14, 2013

关于python - 使用多个 'for' 循环解码嵌套的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16548917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com