0

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.

skr
2,32620 silver badges23 bronze badges
asked Aug 14, 2017 at 8:14

3 Answers 3

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]
answered Aug 14, 2017 at 8:16
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! I did wonder why my json file started and ended with a [ and ] instead of {}
0

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
answered Aug 14, 2017 at 8:21

Comments

0

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"]
answered Aug 14, 2017 at 8:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.