2017-01-23 32 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"] 
相關問題