2017-01-23 85 views
1

我一直在研究这段代码几个小时,试图通过提供的json数据迭代一堆东西。可以弄清楚如何正确迭代这些嵌套列表和对象。通过json数据与Python进行交互

import json 

data = """ 
{ 
"tracks": "1", 
"timeline": { 
"0.733251541": [ 
    { 
    "id": 1, 
    "bounds": { 
     "Width": 0.5099463905313426, 
     "Height": 0.2867199993133546, 
     "Y": 0.4436400003433228, 
     "X": 0.4876505160745349 
    } 
    } 
], 
"0.965": [ 
    { 
    "id": 1, 
    "bounds": { 
     "Width": 0.4205311330135182, 
     "Height": 0.2363199994340539, 
     "Y": 0.2393400002829731, 
     "X": 0.1593787633901481 
    } 
    } 
], 
"1.098224": [ 
    { 
    "id": 1, 
    "bounds": { 
     "Width": 0.4568560813801344, 
     "Height": 0.2564799993857742, 
     "Y": 0.1992600003071129, 
     "X": 0.1000513407532317 
    } 
    } 
] 
    }, 
"taggedTracks": { 
"1": "dirk" 
} 
} 
""" 

json = json.loads(data) 

for a in json["timeline"]: 
    for b in a: 
     for c in b["bounds"]: 
      print a, c["Width"], c["Height"], c["Y"], c["X"] 

有人可以引导我在正确的方向如何处理提供的JSON数据?

我收到以下错误消息。

Traceback (most recent call last): 
    File "<stdin>", line 3, in <module> 
TypeError: string indices must be integers 

回答

2

您正在获取TypeError,因为在每个“时间轴”值中首先出现一个列表。您必须使用索引0获取该列表的第一个值。然后,您可以解析其余的部分。

希望下面的代码帮助:

所有的
import json 

data = """ 
{ 
"tracks": "1", 
"timeline": { 
"0.733251541": [ 
{ 
    "id": 1, 
    "bounds": { 
    "Width": 0.5099463905313426, 
    "Height": 0.2867199993133546, 
    "Y": 0.4436400003433228, 
    "X": 0.4876505160745349 
    } 
} 
], 
"0.965": [ 
{ 
    "id": 1, 
    "bounds": { 
    "Width": 0.4205311330135182, 
    "Height": 0.2363199994340539, 
    "Y": 0.2393400002829731, 
    "X": 0.1593787633901481 
    } 
} 
], 
"1.098224": [ 
{ 
    "id": 1, 
    "bounds": { 
    "Width": 0.4568560813801344, 
    "Height": 0.2564799993857742, 
    "Y": 0.1992600003071129, 
    "X": 0.1000513407532317 
    } 
} 
] 
}, 
"taggedTracks": { 
"1": "dirk" 
} 
} 
""" 

test_json = json.loads(data) 

for num, data in test_json["timeline"].iteritems(): 
    print(num+":") 
    bounds = data[0]["bounds"] 
    for bound, value in bounds.iteritems(): 
     print('\t'+bound+": "+str(value)) 
0

首先,这不是一个好主意使用的名称json的变量,因为这是该模块的名称。我们用j代替。

无论如何,当你做json.loads(),你会得到一个dict。当您迭代for a in <dict>时,您将返回键列表(仅)。您可以改为使用iteritems()重复键和值,如:

for k, a in j['timeline'].iteritems(): 
    for b in a: 
     c = b['bounds'] 
     print k, c["Width"], c["Height"], c["Y"], c["X"]