skip to Main Content

I have a json object as below:
idp =

enter image description here

I want to loop over this object to extract just the uuid and origin fields. I have written this python script:

x = 0

for x in idp:

    idpUUID = idp['dataObject'][x]['uuid']

    idpName = idp['dataObject'][x]['origin']

    if x>0:

        break

But in the for loop for x=0, the value of x is taken as "dataObject" and not integers to loop.

Is there any other way I can loop in the json object so that I can get all uuid fields in idpUUID and origin fields in idpName?

2

Answers


  1. When you traverse a dictionary in Python, the value of x will be each key in the dictionary. Your dictionary only has one key (dataObject) so it sets this as the value of x. You can modify your code like this:

    for x in idp['dataObject']:
        idpUUID = x['uuid']
        idpName = x['origin']
    
        # do something with your data here
    

    Instead of traversing the dictionary, this will traverse the list that is the value of the key dataObject in your dictionary. With each iteration of the loop, x will be one of the objects in the list.

    When you become more advanced with Python, you can make this code even more concise with list comprehension like in Zombro’s answer.

    Login or Signup to reply.
  2. two flavors to start

    [{'uuid': d['uuid'], 'origin': d['origin']} for d in d['dataObject']]
    
    [{ k: v for k,v in d.items() if k in ['uuid', 'origin']} for d in d['dataObject']]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search