I have a json file that looks like this:
[
{
"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
}
]
}
]
When I do
H = {}
with open('train.json', 'r') as json_data:
H = json.load(json_data)
print(H)
It prints out this
How do I access the rectangle values of each image? I've tried
H['image_path:'][os.path.join(directory, filename)]
but that returns
TypeError: list indices must be integers or slices, not str
Any help would be appreciated.
3 Answers 3
Your json file contains a list of dictionaries, which means that you first need to loop through the list, before accessing the contents of the dictionaries.
e.g.
for items in H:
if items['image_path'] == os.path.join(directory, filename):
print items['rects']
If your json had looked like this, you would be able to access the entries like you are expecting.
{
"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
}
]
}
}
e.g.
print H['train640x480/2d4_2.bmp']['rects]
1 Comment
You should first put a number as a index to access the first list. Your json data is structured as a list then dictionary then list then dictionary of the vertices. Your query should be
H[0]["rects"][0] # the fist rectangle dictionary
And
H[1]["rects"][0] # the second rectangle dictionary
Comments
Try this code
print H[0]["image_path"]
print H[0]["rects"][0]["y2"]
print H[1]["image_path"]
print H[1]["rects"][0]["y2"]