-1

I have a function in python which is fetching the data in JSON format and I need to get the value of one item and store it in variable so I could use it another function

import requests
import json
import sys
def printResponse(r):
    print '{} {}\n'.format(json.dumps(r.json(),
    sort_keys=True,
    indent=4,
    separators=(',', ': ')), r)
r = requests.get('https://wiki.tourist.com/rest/api/content',
    params={'title' : 'Release Notes for 1.1n1'},
    auth=('ABCDE', '*******'))
printResponse(r)
getPageid = json.loads(r)
value = int(getPageid['results']['id'])

I am trying to get the value of id(160925) item in variable "value" so I could use it another function

Below is the JSON OUTPUT

{
    "_links": {
        "base": "https://wiki.tourist.com",
        "context": "",
        "self": "https://wiki.tourist.com/rest/api/content?title=Notes+for+1.1u1"
    },
    "limit": 25,
    "results": [
        {
            "_expandable": {
                "ancestors": "",
                "body": "",
                "children": "/rest/api/content/160925/child",
                "container": "",
                "descendants": "/rest/api/content/160925/descendant",
                "history": "/rest/api/content/160925/history",
                "metadata": "",
                "operations": "",
                "space": "/rest/api/space/Next",
                "version": ""
            },
            "_links": {
                "self": "https://wiki.tourist.com/rest/api/content/160925412",
                "tinyui": "/x/5IaXCQ",
                "webui": "/display/Next/Notes+for+1.1u1"
            },
            "extensions": {
                "position": "none"
            },
            "id": "160925",
            "status": "current",
            "title": "Notes for 1.1u1",
            "type": "page"
        }
    ],
    "size": 1,
    "start": 0
} <Response [200]>
unknown
  • 1,815
  • 3
  • 26
  • 51

1 Answers1

1

It looks like the "results" key in the JSON response corresponds to a list, so you'll want to index into that list to get a dict.

E.g. getPageid['results'][0]['id'] should return you the string value of the "id" key for the first object in the "results" list

Ryan Baker
  • 193
  • 7
  • I am getting this error getPageid = json.loads(r) File "C:\Python27\lib\json\__init__.py", line 339, in loads return _default_decoder.decode(s) File "C:\Python27\lib\json\decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer – unknown May 15 '17 at 21:47
  • thanks for giving me the right direction.I am able to get the result now ver = int(info['results'][0]['id']) print ver – unknown May 16 '17 at 02:53