Python:将JSON对象附加到嵌套列表

Python:将JSON对象附加到嵌套列表,json,python-2.7,list,nested,Json,Python 2.7,List,Nested,我尝试遍历一个IP地址列表,从url中提取JSON数据,并尝试将JSON数据放入嵌套列表中 似乎我的代码正在一次又一次地覆盖我的列表,并且只显示一个JSON对象,而不是我指定的多个JSON对象 这是我的密码: for x in range(0, 10): try: url = 'http://' + ip_addr[x][0] + ':8080/system/ids/' response = urlopen(url) json_obj =

我尝试遍历一个IP地址列表,从url中提取JSON数据,并尝试将JSON数据放入嵌套列表中

似乎我的代码正在一次又一次地覆盖我的列表,并且只显示一个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对象附加到列表中,然后将“name”和“serial”值提取到嵌套列表中?

试试这个

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
在代码中,您只需要获取最后的请求数据

最好是使用append并避免列表理解

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
试试这个

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
在代码中,您只需要获取最后的请求数据

最好是使用append并避免列表理解

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

尝试将代码分解成更小、更容易理解的部分。这将帮助您诊断发生了什么

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

尝试将代码分解成更小、更容易理解的部分。这将帮助您诊断发生了什么

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

请正确缩进您的代码。。。我修好了吗?@WillemVanOnsem是的,你修好了,很抱歉。谢谢请正确缩进您的代码。。。我修好了吗?@WillemVanOnsem是的,你修好了,很抱歉。谢谢非常感谢你。这似乎对我有效,从这一方面看它是如何工作的,这让我明确地了解到我应该如何解释我的清单。太棒了,非常感谢你!非常感谢你。这似乎对我有效,从这一方面看它是如何工作的,这让我明确地了解到我应该如何解释我的清单。太棒了,非常感谢你!