I have a json object as below:
idp =
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
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: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.
two flavors to start