解析json数组到Python列表
问题描述:
我已经创建了我自己的json数据与我想解析成python列表的数组。不过,我一直有这个麻烦。解析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列表中?
答
问题是你的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]
]