Reputation: 969
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?
Upvotes: 0
Views: 892
Reputation: 1231
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
Upvotes: 1
Reputation: 2738
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']])
Upvotes: 1