Python:将JSON对象附加到嵌套列表 [英] Python: Append JSON objects to nested list
问题描述
我试图遍历IP地址列表,并从URL中提取JSON数据,然后尝试将该JSON数据放入嵌套列表中.
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.
似乎我的代码一遍又一遍地覆盖了我的列表,并且只会显示一个JSON对象,而不是我指定的许多对象.
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.
这是我的代码:
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"值提取到嵌套列表中?
How can I append my JSON objects into a list, and then extract the 'name' and 'serial' values into a nested list?
推荐答案
尝试一下
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
最好是使用append并避免列表理解
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
这篇关于Python:将JSON对象附加到嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!