【问题标题】:Python: Append JSON objects to nested listPython:将 JSON 对象附加到嵌套列表
【发布时间】:2017-11-17 07:39:23
【问题描述】:

我正在尝试遍历 IP 地址列表,并从我的 url 中提取 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 对象附加到列表中,然后将“名称”和“序列”值提取到嵌套列表中?

【问题讨论】:

  • 请正确缩进您的代码...我是否正确修复了它?
  • @WillemVanOnsem 是的,你有,对此感到抱歉。谢谢!

标签: json python-2.7 list nested


【解决方案1】:

试试这个

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

在您的代码中,您只获取最后的请求数据

最好使用追加并避免列表理解

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

【讨论】:

  • 非常感谢。这似乎对我有用,从这方面看它是如何工作的,可以明确地了解我应该如何解释我的列表。太棒了,非常感谢!
【解决方案2】:

尝试将您的代码分解成更小、更易于消化的部分。这将帮助您诊断正在发生的事情。

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

【讨论】:

    猜你喜欢
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2021-12-10
    • 2015-08-10
    • 2021-12-01
    相关资源
    最近更新 更多