Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find string within JSON with Python

Tags:

python

json

I'm currently getting a very long JSON and I'm trying to pick out 2 pieces of information from it through Python 2.7.

The JSON looks roughly like this:

{
  'device': [
    {
      'serial': '00000000762c1d3c',
      'registered_id': '019'
    },
    {
      'serial': '000000003ad192f2',
      'registered_id': '045'
    },
    {
      'serial': '000000004c9898aa',
      'registered_id': '027'
    }
  ],
}

Within this JSON I'm looking for a specific serial that might match with one in the JSON. If it does, it should print out the registered_id as well.

I've tried using a simple script, even without the registered_id but I'm getting nowhere.:

if '00000000762c1d3c' not in data['device']:
        print 'not there'
else:
        print 'there'

Thanks for your suggestions!

like image 590
user5740843 Avatar asked Jan 08 '17 15:01

user5740843


People also ask

How do I find a word in a JSON file in Python?

Example-1: Search key in simple JSON data Here, a variable named customerData is defined to store the JSON data. The value of the key will be taken as input from the user. loads() method of JSON module is used to load JSON data in the variable named customer. Next, 'in' operator is used to search the key.

How do you check if a key exists in a JSON string in Python?

Check if the key exists or not in JSON if it is present directly to access its value instead of iterating the entire JSON. Note: We used json. loads() method to convert JSON encoded data into a Python dictionary. After turning JSON data into a dictionary, we can check if a key exists or not.


2 Answers

first, your input isn't json. Json uses double quotes. But suppose you successfully loaded it with json, it's now a dictionary, called d.

Then you can scan all sub-dicts of d and test serial key against your value, stopping when found using any and a generator comprehension:

print(any(sd['serial']=='00000000762c1d3c' for sd in d['device']))

returns True if serial found False otherwise.

like image 177
Jean-François Fabre Avatar answered Oct 12 '22 20:10

Jean-François Fabre


date['device'] contains a list of objects, so you should treat it as such and iterate over them:

for element in data['device']:
    if element['serial'] == '00000000762c1d3c':
        print 'there'
        print element['registered_id']
        break
else:
    print 'not there'

This is using the somehow lesser-known for-else construct: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

like image 41
DeepSpace Avatar answered Oct 12 '22 22:10

DeepSpace