使用多个“for”循环解码嵌套JSON

2024-10-06 12:41:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手(上周),已经达到了极限。在这上面花了三天时间,我大部分时间都在stackoverflow,但是我不知道怎么走得更远!

Json有多个嵌套数组。它可以包含三个(如下例(json.txt)或30个。我需要遍历每一个,然后深入到“局”,最后得到“边线”的值。这是我困惑的最后一步。有人能建议吗?

你的绝望

威尔

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'?

Tags: theintxtjsonurlfordataget
3条回答

它看起来很难看,但是您可以改进它,但是这里列出了Dict和List混合的任意深度:

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'

def dig_down(partial_json_list, depth):
    if type(partial_json_list) is list:
        for i in range(len(partial_json_list)):
            print 'index', i, ' at depth', depth,' has', len(partial_json_list[i]) , 'elements'
            if len(partial_json_list[i]) > 1:
                dig_down(partial_json_list[i],depth+1)
    else:
        for k in partial_json_list:
            print 'item at depth', depth, 'equals', k#, ' & has', len(partial_json_list[k]) , 'elements'
            if type(partial_json_list) is list or type(partial_json_list) is dict:
                try:
                    if len(partial_json_list[k]) > 1:
                        dig_down(partial_json_list[k],depth+1)
                except:
                    pass
            else:
                print partial_json_list[k]

# get the content
the_data = json_string.json()
print 'the_data has length ', len(the_data)
dig_down(the_data,0)

首先,不要使用索引,而是直接在列表上循环;这样就可以给它们取有意义的名称。顶层是一个条目列表,每个条目是一个具有'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
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 d in the_data[index]['innings']:
        print d['wickets']

相关问题 更多 >