【问题标题】:Using Response of Confluence Rest API使用 Confluence Rest API 的响应
【发布时间】:2020-06-26 09:56:23
【问题描述】:

我正在我们的 Confluence Cloud 实例中执行创建空间和页面的批量操作。我不是一个特别的程序员。在使用 Python 运行 API 后获得的响应时需要一些帮助。输出为 Json 格式。如果这是输出,请告诉我如何访问标题和 ID -

{
"content": {
    "id": "398852913",
    "type": "page",
    "status": "current",
    "title": "Test Project Name 1 SOW",
    "childTypes": {},
    "macroRenderedOutput": {},
    "restrictions": {},
    "_expandable": {
        "container": "",
        "metadata": "",
        "extensions": "",
        "operations": "",
        "children": "",
        "history": "/rest/api/content/398852913/history",
        "ancestors": "",
        "body": "",
        "version": "",
        "descendants": "",
        "space": "/rest/api/space/TestSpace1",
    },
    "_links": {
        "webui": "/spaces/TestSpace1/pages/398852913/Test+Project+Name+1++SOW",
        "self": "https://enerzinx.atlassian.net/wiki/rest/api/content/398852913",
        "tinyui": "/x/MQPGFw",
    },
},
"title": "Test Project Name 1 SOW",
"excerpt": "file-list",
"url": "/spaces/TestSpace1/pages/398852913/Test+Project+Name+1++SOW",
"resultGlobalContainer": {
    "title": "TestSpace1",
    "displayUrl": "/spaces/TestSpace1",
},
"breadcrumbs": [],
"entityType": "content",
"iconCssClass": "aui-iconfont-page-default",
"lastModified": "2020-06-24T06:17:32.333Z",
"friendlyLastModified": "Jun 24, 2020",
"score": 0.59390986,
}

【问题讨论】:

  • title = response["title"]id = response["content"]["id"]

标签: python json confluence-rest-api


【解决方案1】:

如果您的响应是 JSON 格式的字符串,您首先需要将 JSON 解析为字典。为此,您可以使用json 模块,它是标准模块集的一部分。解析 JSON 后,您可以使用字典查找访问键。

>>> import json
>>>
>>> json_string = '{"foo": "bar"}'
>>> json_dict = json.loads(json_string)
>>> json_dict["foo"]
'bar'

看起来您的响应 JSON 将生成一个嵌套字典,因此标题的路径类似于 json_dict["foo"]["bar"]

【讨论】:

  • 感谢@Dylan 的回复。这是我得到的响应输出的一部分“ {'results': [{'content': {'id': '398852905', 'type': 'page', 'status': 'current', 'title' : 'Test Project Name 1 PT', 'childTypes': {}," 用我的代码。我尝试包含 json.loads 语句 "res = json.loads(response.text) resJsonDict = json.loads(res) 。它抛出此错误“引发 TypeError(f'JSON 对象必须是 str、bytes 或 bytearray,'”请让我知道我错过了什么。
  • 如果您使用requests 库,您应该也可以调用res.json() 来解析JSON。查看结果对象,此请求会为您提供结果列表,尽管 JSON 看起来确实不完整。根据我所见,您可以尝试response["results"][0]["content"]["title"]response["results"][0]["content"]["id"],其中response 是解析后的JSON 响应,0 是您正在读取的标题和ID 的结果索引。
  • 感谢@Dylan - 能够实现我正在尝试使用“pageID = str(res['results'][i]['content']['id'])”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 2019-01-22
  • 1970-01-01
相关资源
最近更新 更多