如何从 Python 中的 JSON 输出中获取任何项目的值?
How to Fetch the value of any item from the JSON output in Python?
我在 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]>
看起来 JSON 响应中的 "results"
键对应于一个列表,因此您需要索引到该列表以获取字典。
例如getPageid['results'][0]['id']
应该 return 你 "results"
列表
中第一个对象的 "id"
键的字符串值
我在 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]>
看起来 JSON 响应中的 "results"
键对应于一个列表,因此您需要索引到该列表以获取字典。
例如getPageid['results'][0]['id']
应该 return 你 "results"
列表
"id"
键的字符串值