Ryan Litwiller
Ryan Litwiller

Reputation: 507

Accessing nested JSON elements in Python

New to Python and I'm not sure im encoding my request as JSON properly. I am trying to be able to access specific elements within the JSON. This is what I have:

import requests
import json

url = "sample.com"
access_token "xxxxx"

headers = {
    'authorization': access_token,
    'cache-control': "no-cache"
    }

response = requests.request("GET", url, headers=headers)

jsonvar = response.json()
print(jsonvar)

This gives me:

{u'sleep': 
     [{u'logId': 11208762595, 
       u'dateOfSleep': u'2016-03-23', 
       u'isMainSleep': True, 
       u'startTime': u'2016-03-22T23:43:30.000', 
       u'restlessCount': 7, 
       u'duration': 12540000, 
       u'restlessDuration': 13, 
       u'minuteData': [{u'value': u'2', u'dateTime': u'23:43:30'}, 
                       {u'value': u'1', u'dateTime': u'23:44:30'}],                         
       u'awakeCount': 1, 
       u'minutesAfterWakeup': 0}], 
 u'summary': 
      {u'totalTimeInBed': 418, 
       u'totalMinutesAsleep': 395, 
       u'totalSleepRecords': 2}}

I've altered the output in an attempt to make it more readable. Anyways I would like to assign specific element values to variables such as isMainSleep etc.

I've tried something like this:

myvar = jsonvar['isMainSleep'] 

I was able to get this to work in a different situation but none of the data was nested which seems to be the difference here.

Upvotes: 2

Views: 5154

Answers (2)

DevShark
DevShark

Reputation: 9102

You simply need to access each dictionary along the way. Like this:

myvar = jsonvar['sleep'][0]['isMainSleep']

You access the list associated with the key sleep, then its first element, which is a dictionary. Finally the value associated with the key isMainSleep.

Note that you do not need to add the prefix 'u' in front of your keys.

In answer to your comment, you could output this as a json like this:

print json.dumps(myvar)

Upvotes: 5

ashishsingal
ashishsingal

Reputation: 2978

You have a nested list and dictionary here, and the top level keys are sleep and summary. So try myvar = jsonvar['sleep'][0]['isMainSleep'].

Upvotes: 1

Related Questions