Santino Santino - 3 months ago 13
JSON Question

Python Rest API - looping through dictionary object

Python newbie here

I am querying an API and get a json string like this:

{
"human": [
{
"h": 310,
"prob": 0.9588886499404907,
"w": 457,
"x": 487,
"y": 1053
},
{
"h": 283,
"prob": 0.8738606572151184,
"w": 455,
"x": 1078,
"y": 1074
},
{
"h": 216,
"prob": 0.8639854788780212,
"w": 414,
"x": 1744,
"y": 1159
},
{
"h": 292,
"prob": 0.7896996736526489,
"w": 442,
"x": 2296,
"y": 1088
}
]
}


I figured out how to get a dict object in python

json_data = json.loads(response.text)


But I am not sure how to loop through the dict object. I have tried this, but this prints out the key repeatedly, how do I access the parent object and child objects?

for data in json_data:
print data
for sub in data:
print sub

Answer

See the following examples:

print json_data['human']
>> [
      {
        "h": 310,
        "prob": 0.9588886499404907,
        "w": 457,
        "x": 487,
        "y": 1053
      },
      {
        "h": 283,
        "prob": 0.8738606572151184,
        "w": 455,
        "x": 1078,
        "y": 1074
      },
      .
      .
  ]


for data in json_data['human']:
    print data
>> {
     "h": 310,
     "prob": 0.9588886499404907,
     "w": 457,
     "x": 487,
     "y": 1053
   } 

   {
     "h": 283,
     "prob": 0.8738606572151184,
     "w": 455,
     "x": 1078,
     "y": 1074
    }
.
.


for data in json_data['human']:
    print data['h']
>> 310
   283

In order to loop through the keys:

for type_ in json_data:
    print type_
    for location in json_data[type_]:
        print location

type_ is used to avoid Python's built-it type. You can use whatever name you see fit.

Comments