0

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 overwriting my list over and over, and will only show one JSON object, instead of the many I have specified.

Here's my code:

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

How can I append my JSON objects into a list, and then extract the 'name' and 'serial' values into a nested list?

2
  • Please properly indent your code... Did I fixed it correctly? Commented Jun 15, 2017 at 0:51
  • @WillemVanOnsem Yes you have, sorry about that. Thanks! Commented Jun 15, 2017 at 1:05

2 Answers 2

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 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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. This has seemed to work for me and looking at how it works from this side gives a definite insight into how I should have been interpreting my lists. Awesome, thank you so much!
1

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']])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.