gpt4 book ai didi

python - 从 Python 中的响应中读取特定的 JSON 对象

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:14 26 4
gpt4 key购买 nike

当您的 JSON 响应包含多个 JSON 对象时,如何使用 Python 提取 JSON 中的特定对象?

例如,对于以下 JSON 响应,其中包含三个对象。

{
"_links": {
"base": "REDACTED",
"context": "",
"self": "REDACTED"
},
"limit": 20,
"results": [
{
"_expandable": {
"ancestors": "",
"body": "",
"children": "",
"container": "",
"descendants": "",
"extensions": "",
"history": "/rest/api/content/198121503/history",
"metadata": "",
"operations": "",
"space": "/rest/api/space/ReleaseNotes",
"version": ""
},
"_links": {
"self": "REDACTED",
"tinyui": "/x/HxjPCw",
"webui": "UNIQUE_URL_HERE"
},
"id": "198121503",
"status": "current",
"title": "Unique Title of Content",
"type": "page"
},
{
"_expandable": {
"ancestors": "",
"body": "",
"children": "",
"container": "",
"descendants": "",
"extensions": "",
"history": "/rest/api/content/197195923/history",
"metadata": "",
"operations": "",
"space": "/rest/api/space/ReleaseNotes",
"version": ""
},
"_links": {
"self": "REDACTED",
"tinyui": "/x/k-jACw",
"webui": "UNIQUE_URL_HERE"
},
"id": "197195923",
"status": "current",
"title": "Unique Title of Content",
"type": "page"
},
{
"_expandable": {
"ancestors": "",
"body": "",
"children": "",
"container": "",
"descendants": "",
"extensions": "",
"history": "/rest/api/content/198121203/history",
"metadata": "",
"operations": "",
"space": "/rest/api/space/ReleaseNotes",
"version": ""
},
"_links": {
"self": "REDACTED",
"tinyui": "/x/8xbPCw",
"webui": "UNIQUE_URL_HERE"
},
"id": "198121203",
"status": "current",
"title": "Unique Title of Content",
"type": "page"
}
],
"size": 3,
"start": 0

}

如何检索响应中特定对象的 ID 和 TITLE?

我在其他线程中读到,当您使用 json.loads(your_json) 时,它就变成了一本字典。如果是这样的话,如果这些数据存储为字典,我该如何提取这些数据?

更新

让我澄清一下,因为也许我没有清楚地看到或解释这一点。

这是循环遍历所有内容的唯一选择吗?没有一个选项可以让我获取第二个 JSON 对象并返回 ID 和标题吗?如果是这样,为什么我不应该创建一个自定义对象,将每个 JSON 对象中我想要的项目存储到数组中,然后我就可以访问数组中的每个对象?

最佳答案

将响应转换为 json 后,您可以只使用关键属性。

for result in data['results']:
print("id: {}, title: {}".format(result['id'], result['title']))

正如您所提到的,您可以使用 json.load 将字符串转换为字典。但如果您使用 requests库,只需使用response.json即可获取所需格式的数据。

关于python - 从 Python 中的响应中读取特定的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38334964/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com