当你有一个包含多个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对象存储到一个数组中,然后我可以访问数组中的每个对象?
答案 0 :(得分:1)
将响应转换为json后,您可以使用关键属性。
for result in data['results']:
print("id: {}, title: {}".format(result['id'], result['title']))
正如您所提到的,您可以使用json.load将字符串转换为字典。但是如果你正在使用requests库,只需使用response.json来获取所需格式的数据。
答案 1 :(得分:0)
在将字符串加载到json对象后,使用括号表示法来访问键。循环遍历结果键,直到找到所需的对象,如下所示:
j = json.loads(your_json)
for r in j["results"]:
if r["title"] == "Something":
print(r["id"])
print(r["title"])