【问题标题】:How to Fetch the value of any item from the JSON output in Python?如何从 Python 中的 JSON 输出中获取任何项目的值?
【发布时间】:2017-05-15 21:28:18
【问题描述】:

我在 python 中有一个函数,它以 JSON 格式获取数据,我需要获取一个项目的值并将其存储在变量中,以便我可以使用另一个函数

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'])

我正在尝试在变量“value”中获取 id(160925) 项的值,以便可以将其用作另一个函数

下面是 JSON 输出

{
    "_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]>

【问题讨论】:

    标签: python python-2.7 confluence-rest-api


    【解决方案1】:

    看起来 JSON 响应中的 "results" 键对应于一个列表,因此您需要在该列表中建立索引以获取字典。

    例如getPageid['results'][0]['id'] 应该返回"id" 键的字符串值,用于"results" 列表中的第一个对象

    【讨论】:

    • 我收到此错误 getPageid = json.loads(r) File "C:\Python27\lib\json_init_.py",第 339 行,加载返回 _default_decoder .decode(s) 文件“C:\Python27\lib\json\decoder.py”,第 364 行,在 decode obj 中,end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError : 预期的字符串或缓冲区
    • 感谢您给我正确的方向。我现在可以得到结果 ver = int(info['results'][0]['id']) print ver
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多