SuperCiocia
SuperCiocia

Reputation: 1971

Searching a JSON file for a specific value, python

I have a JSON file that looks like this:

enter image description here

I have a list of device ID's, and I'd like to search my JSON for a specific value of the id, to get the name.

The data that is now is JSON format used to be in XML format, for which I used to do this:

device = xml.find("devices/device[@id=\'%s\']" %someDeviceID)
deviceName = device.attrib['name']

--

So far based on answers online I have managed to search the JSON for a jey, but I haven't yet managed to search for a value.

Upvotes: 3

Views: 9492

Answers (1)

Joost Luijben
Joost Luijben

Reputation: 173

Personally to read a json file I use the jsondatabase module. Using this module I would use the following code

from jsondb.db import Database 

db = Database('PATH/TO/YOUR/JSON/FILE')
for device in db['devices']:
    if device['id'] == 'SEARCHEDID':
        print(device['name'])

Of course when your json is online you could scrape it with the requests module and then parse it to the jsondatabase module

Upvotes: 1

Related Questions