2017-06-15 91 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']])