在Python中解析JSON文件的问题

2024-05-02 16:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个json文件,如下所示:

[
 {
  "image_path": "train640x480/2d4_2.bmp",
  "rects": [
   {
    "y2": 152.9,
    "y1": 21.2,
    "x2": 567.3,
    "x1": 410.8
   }
  ]
 },
 {
  "image_path": "train640x480/1dd_1.bmp",
  "rects": [
   {
    "y2": 175.1,
    "y1": 74.7,
    "x2": 483.8,
    "x1": 230.8
   }
  ]
 }
]

当我这么做的时候

H = {}
with open('train.json', 'r') as json_data:
        H = json.load(json_data)
    print(H)

它打印出this

如何访问每个图像的矩形值?我试过了

H['image_path:'][os.path.join(directory, filename)]

但这又回来了

TypeError: list indices must be integers or slices, not str

任何帮助都将不胜感激。你知道吗


Tags: 文件pathimagejsondatawithtrainopen
3条回答

您应该首先将一个数字作为索引来访问第一个列表。json数据的结构是一个列表,然后是字典,然后是列表,最后是顶点字典。您的查询应该是

H[0]["rects"][0] # the fist rectangle dictionary

以及

H[1]["rects"][0] # the second rectangle dictionary

json文件包含一个字典列表,这意味着在访问字典内容之前,首先需要遍历该列表。你知道吗

例如

for items in H:
    if items['image_path'] == os.path.join(directory, filename):
        print items['rects']

如果您的json是这样的,那么您就可以像预期的那样访问条目。你知道吗

{
    "train640x480/2d4_2.bmp":
        {
            "rects": [
                {
                    "y2": 152.9,
                    "y1": 21.2,
                    "x2": 567.3,
                    "x1": 410.8

                }
            ]
        },

    "train640x480/1dd_1.bmp":
        {
            "rects": [
                {
                    "y2": 175.1,
                    "y1": 74.7,
                    "x2": 483.8,
                    "x1": 230.8
                }
            ]
        }
}

例如

print H['train640x480/2d4_2.bmp']['rects]

尝试此代码

print H[0]["image_path"]
print H[0]["rects"][0]["y2"]


print H[1]["image_path"]
print H[1]["rects"][0]["y2"]

相关问题 更多 >