11

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!

1
  • Write a for loop to iterate over the devices. Jan 8, 2017 at 15:18

3 Answers 3

8

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.

7

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

1
  • is it pissuble to check if a string is contained at all in the serial. lets say you want to search and store all the serial number that have a 3 in it. and return the first and second serial number in an object or array.... Jun 12, 2018 at 7:51
0

Maybe 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 construct lists in a very natural, easy way, like a mathematician is used to do.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.