麻烦与蟒蛇
问题描述:
阅读JSON文件,我有一个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)
如何访问每个图像的矩形值?我试过
H['image_path:'][os.path.join(directory, filename)]
但返回
TypeError: list indices must be integers or slices, not str
任何帮助,将不胜感激。
答
您的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]
答
您应该首先将一个数字作为索引访问第一个列表。你的json数据的结构是一个列表,然后是字典列表,然后列出顶点字典。您的查询应该是
H[0]["rects"][0] # the fist rectangle dictionary
而且
H[1]["rects"][0] # the second rectangle dictionary
答
试试这个代码
print H[0]["image_path"]
print H[0]["rects"][0]["y2"]
print H[1]["image_path"]
print H[1]["rects"][0]["y2"]
非常感谢您!我确实想知道为什么我的json文件开始并以[和]而不是{}结束, –