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.
jsonvar['sleep']['isMainSleep']isMainSleepis in a dictionary nested inside a list nested inside another dictionary. You wantjsonvar[u'sleep'][0][u'isMainSleep']. Notice theuin front because these are unicode strings and the[0]because it's the first item in the list. You might want to add some error checking.