Skip to content Skip to sidebar Skip to footer

Python: Append Json Objects To Nested List

I'm trying to iterate through a list of IP addresses, and extracting the JSON data from my url, and trying to put that JSON data into a nested list. It seems as if my code is overw

Solution 1:

try this

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

in your code you where only getting the last requests data

Best would be using append and avoiding list comprehension

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

for x in camera_details:
    print x

Solution 2:

Try breaking up your code into smaller, easier to digest parts. This will help you to diagnose what's going on.

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

Post a Comment for "Python: Append Json Objects To Nested List"