Find string in JSON using Python

I am currently getting a very long JSON and I am trying to select 2 pieces of information from it through Python 2.7.

JSON looks something like this:

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

Inside this JSON, I'm looking for a specific series that can match one in JSON. If so, it should also print register_id.

I tried using a simple script, even without register_id, but I can't go anywhere .:

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

Thanks for your suggestions!

+6
source share
3 answers

date['device'] contains a list of objects, so you should consider them 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 uses the somewhat less-known for-else : https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

+4
source

Firstly, your input is not json. Json uses double quotes. But suppose you successfully downloaded it using json, now it is a dictionary called d .

Then you can scan all the d sub-icons and check the serial key for its value, stopping when detecting with any and understanding the generator:

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

returns True if the serial search is False otherwise.

+6
source

Perhaps this will help you:

 if [x for x in data['device'] if x.get('serial')=='00000000762c1d3c']: print "IN" else: print "NOT" 

Python: List Comprehensions can be used to create lists in a very natural and simple way, as a mathematician does.

0
source

Source: https://habr.com/ru/post/1013881/


All Articles