Jamie4840 Jamie4840 - 2 years ago 104
JSON Question

Python 3 JSON - Select by value rather than index?

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:

{"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
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
value meaning I'd do something like:


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
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
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?

Answer Source

Minor note: this really has nothing to do with JSON. Once you've parsed the data, it's no longer JSON, but it's regular data in memory (lists, strings, dictionaries, etc.)

An easy way to do this is with a loop:

for device in data['device']:
    if device['id'] == 5:
        print('Device:', device['name'])
    print('No such device')

You can also do this with comprehensions or other sophisticated (and terse) ways, but the above method is perhaps the more straightforward and simple.

There is also a system called JSONPath (with its Python module) which can let you express the queries in a more declarative and natural fashion.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download