2

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.

3
  • 1
    jsonvar['sleep']['isMainSleep'] Commented Mar 28, 2016 at 21:18
  • 1
    isMainSleep is in a dictionary nested inside a list nested inside another dictionary. You want jsonvar[u'sleep'][0][u'isMainSleep']. Notice the u in 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. Commented Mar 28, 2016 at 21:21
  • @solarc your suggestion worked! However because its just a comment I can't accept it as the answer. Is there a better way to output this data so its actually in JSON format? Commented Mar 28, 2016 at 21:26

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.