2017-06-15 88 views
0

我想遍歷IP地址列表,並從我的URL中提取JSON數據,並試圖將該JSON數據放入嵌套列表中。Python:將JSON對象追加到嵌套列表

看起來好像我的代碼一遍又一遍覆蓋我的列表,並且只顯示一個JSON對象,而不是我指定的多個對象。

這裏是我的代碼:

for x in range(0, 10): 
    try: 
     url = 'http://' + ip_addr[x][0] + ':8080/system/ids/' 
     response = urlopen(url) 
     json_obj = json.load(response) 
    except: 
     continue 

    camera_details = [[i['name'], i['serial']] for i in json_obj['cameras']] 

for x in camera_details: 
    #This only prints one object, and not 10. 
    print x 

如何將我的JSON對象追加到一個列表,然後提取「名」和「串聯」值到嵌套表?

+0

請正確縮進代碼...我修正了它嗎? –

+0

@WillemVanOnsem是的,對此抱歉。謝謝! – juiceb0xk

回答

1

試試這個

camera_details = [] 
for x in range(0, 10): 
    try: 
     url = 'http://' + ip_addr[x][0] + ':8080/system/ids/' 
     response = urlopen(url) 
     json_obj = json.load(response) 
    except: 
     continue 

    camera_details.extend([[i['name'], i['serial']] for i in json_obj['cameras']]) 

for x in camera_details: 
    print x 
在你的代碼

你那裏只得到了最後的請求數據

最好將使用追加和避免列表理解

camera_details = [] 
for x in range(0, 10): 
    try: 
     url = 'http://' + ip_addr[x][0] + ':8080/system/ids/' 
     response = urlopen(url) 
     json_obj = json.load(response) 
    except: 
     continue 
    for i in json_obj['cameras']: 
     camera_details.append([i['name'], i['serial']]) 

for x in camera_details: 
    print x 
+0

非常感謝。這似乎對我有用,並從這方面看它是如何工作的,從而明確瞭解​​我應該如何解釋我的列表。真棒,非常感謝你! – juiceb0xk

1

儘量將你的代碼更小,更容易消化的部分。這將幫助您診斷正在發生的事情。

camera_details = [] 
for obj in json_obj['cameras']: 
    if 'name' in obj and 'serial' in obj: 
     camera_details.append([obj['name'], obj['serial']])