3

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.

6
  • data['devices'][someDeviceId]. Parse it with data = json.loads(...) before if you need. You owe me a beer. ;) Commented Jan 8, 2018 at 17:28
  • You can import json and use json.loads(open(filename, 'r').read()) to read this file into a python object, then do what @freakish posted above. And you owe him a beer. ETA: Use data['devices'].get('someDeviceId') if you're not sure if 'someDeviceId` exists. Commented Jan 8, 2018 at 17:29
  • @freakish When I do <code>data['devices']</code> I get <code>[{u'id' : u'7DD88039CFE09C3', u'name' : u'Watchdog 15 (Internal)'}, {u'id': u'788B5635DC2EBCD2', u'name': u'Smoke Alarms'}, ... }] </code> etc. Commented Jan 8, 2018 at 18:02
  • And if I try to do <code> data['devices']["788B5635DC2EBCD2"]</code> or similar it tells me that I need to put integers not strings. Commented Jan 8, 2018 at 18:03
  • 1
    @SuperCiocia Ah, devices is an array. Fair enough. Then you have to search it, my friend. Either convert it to a dict (assuming ids are unique) or search linearly: next(dev for dev in data['devices'] if dev['id'] == someId). Commented Jan 8, 2018 at 18:04

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes it does. If you have multiple of the same ID's and you want all of them, you could add "pass" under the print line
use list comprehension

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.