I've got some data in a JSON file that I'm trying to manipulate. Having not done much with JSON before, I'm wondering if it's possible to select an object by one of its values rather than the index.
Here's my json file:
{"device":[
{"id": 0, "name": "iPhone 6", "width": 750, "height": 1334},
{"id": 1, "name": "iPhone 6 Plus", "width": 1242, "height": 2208},
{"id": 2, "name": "Galaxy S6", "width": 1440, "height": 2560}
]}
I want to select object of id = 0
and print out the name
value. I realise that the typical way to do this would be to select the object via its index value, which in this case matches up with the id
value meaning I'd do something like:
print(json_obj['device'][0]['name'])
That would print the name but it relies on the index being equal to the id, which in an ideal world it would be. Perhaps a better way would be to just take the index as the id
and remove that field altogether so there is no confusion? Seems like a duplicate index now that I think about it, though it exists so that I can store an ID in my database and edit the name
independently in the JSON file yet have something concrete to denote the order (i.e. someone might add a device to the top of the file thus shifting the index of every other device - breaking the whole system). I get the feeling I'm barking up the wrong data structure and there's no way to do something along the lines of:
print(json_obj['device'][id = 0]['name']
Am I right?