2

The json structure

{
    "categories": [{
        "supercategory": "Bottle",
        "id": 1,
        "name": "Bottle"
    },
    {
        "supercategory": "Car",
        "id": 2,
        "name": "Car"
    }]
}

Is read by the following python script:

with open('file.json') as json_data:
    json_info = json.load(json_data)

At some later point, the same script tries to access the data structure in the following way:

json_info['1']['name']
json_info['2']['name']

Where the numbers refer to the "id" field in the json structure. Since that code is obviously inconsistent with the json structure: How do I have to change the json structure to make that work? (Assuming I can't change the script).

3 Answers 3

6

For your code to work, you'll need something like this:

json_info = {
     "1": {"supercategory": "Bottle",
           "name": "Bottle"},
     "2": {"supercategory": "Car",
           "name": "Car"}
     }
Sign up to request clarification or add additional context in comments.

2 Comments

You out clicked me, my friend! But, you did win fair and square by 41 seconds, have an upvote!
@AaronN.Brock Thanks, upvoted you as soon as you posted :)
3

I think what you're looking for is something like this:

{
    "1": {
        "supercategory": "Bottle",
        "id": 1,
        "name": "Bottle"
    },
    "2": {
        "supercategory": "Car",
        "id": 2,
        "name": "Car"
    }
}

Comments

0

Firsty, I would highly recommend using the 'get' method whenever accessing a dictionary in Python. It implicitly handles cases in which the given key(s) are not valid and prevents errors by returning null (or a default value). See this link for more info. So the code would be re-written as json_info.get('1',{}).get('name'). Note the default empty dictionary in the first get - this is to avoid None type errors. Second, if indeed you mean to access objects by their ID STRING (and not int) your JSON data structure would be:

{
  "1": {
    "supercategory": "Bottle",
    "name": "Bottle"
  },
  "2": {
    "supercategory": "Car",
    "name": "Car"
  }
}

Comments

Your Answer

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.