将json数组解析为Python列表

时间:2017-06-23 01:36:17

标签: arrays json python-2.7 list

我已经创建了自己的json数据,我希望将数组解析为python列表。但是,我一直遇到麻烦。

如何将json数组提取到python列表中?

json数据:

[
  {
    "ip": "192.168.241.109", 
    "cameras": 
       {
          "front": "nf091", 
          "inside": "nf067", 
          "right": "004317",
          "rear": "000189",
          "left": "nf084"
       }
  }, 
  {
   "ip": "192.168.241.110",           
   "cameras": 
   {
          "front": "nf091", 
          "inside": "nf067", 
          "right": "004317", 
          "rear": "000189", 
          "left": "nf084"
   }
  }
]

我的json数据有效,所以我不知道为什么我遇到以下代码时出现问题:

system_json = open(json_file)
json_obj = json.load(system_json)

camera_details = [[i['front'], i['rear'], i['left'], i['right'], i['inside']] for i in json_obj['cameras']]

上面的代码段不起作用,因为它会产生list indices must be integers, not str错误。

我做错了什么,如何正确解析我的json数组到python列表?

1 个答案:

答案 0 :(得分:5)

问题是您的JSON“对象”是一个列表,但是您尝试使用字符串(json_obj['cameras'])对其进行索引。

你拥有的是一个JSON数组,其中每个元素都是一个字典,其中包含一个名为"cameras"的键(除此之外)。我相信这段代码可以满足您的需求:

import json

text = """[{"ip": "192.168.241.109", "cameras": {"front": "nf091", "inside": "nf067", "right": "004317", "rear": "000189", "left": "nf084"}}, {"ip": "192.168.241.110", "cameras": {"front": "nf091", "inside": "nf067", "right": "004317", "rear": "000189", "left": "nf084"}}]"""

json_array = json.loads(text)

camera_details = [[i['cameras']['front'], i['cameras']['rear'], i['cameras']['left'], i['cameras']['right'], i['cameras']['inside']] for i in json_array]
print(camera_details)

# Output:
# [['nf091', '000189', 'nf084', '004317', 'nf067'], ['nf091', '000189', 'nf084', '004317', 'nf067']]

修改

可能更清晰/更容易?

camera_details = [
    [
        cameras["front"],
        cameras["rear"],
        cameras["left"],
        cameras["right"],
        cameras["inside"],
    ]
    for cameras in [item["cameras"] for item in json_array]
]