Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested object structure in json format

Tags:

python

json

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).

like image 784
user1934212 Avatar asked Feb 13 '26 18:02

user1934212


2 Answers

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

json_info = {
     "1": {"supercategory": "Bottle",
           "name": "Bottle"},
     "2": {"supercategory": "Car",
           "name": "Car"}
     }
like image 123
zipa Avatar answered Feb 15 '26 07:02

zipa


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"
    }
}
like image 26
Aaron N. Brock Avatar answered Feb 15 '26 08:02

Aaron N. Brock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!