如何从Python中的JSON输出中获取任何项的值?
我在python中有一个函数,它以JSON格式获取数据,我需要获取一个项的值并将其存储在变量中,这样我就可以使用另一个函数了如何从Python中的JSON输出中获取任何项的值?,python,python-2.7,confluence-rest-api,Python,Python 2.7,Confluence Rest Api,我在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
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)项的值,以便将其用于另一个函数
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'])
下面是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]>
{
“_链接”:{
“基础”:https://wiki.tourist.com",
“上下文”:“,
“自我”:https://wiki.tourist.com/rest/api/content?title=Notes+对于+1.1u1“
},
“限制”:25,
“结果”:[
{
“_可扩展”:{
“祖先”:“,
“正文”:“,
“儿童”:“/rest/api/content/160925/child”,
“容器”:“,
“后代”:“/rest/api/content/160925/genderant”,
“历史记录”:“/rest/api/content/160925/history”,
“元数据”:“,
“业务”:“业务”,
“空间”:“/rest/api/space/Next”,
“版本”:”
},
“_链接”:{
“自我”:https://wiki.tourist.com/rest/api/content/160925412",
“tinyui”:“/x/5IaXCQ”,
“webui”:“/display/Next/Notes+用于+1.1u1”
},
“扩展”:{
“位置”:“无”
},
“id”:“160925”,
“状态”:“当前”,
“标题”:“1.1u1的注释”,
“类型”:“页面”
}
],
“大小”:1,
“开始”:0
}
JSON响应中的“results”
键似乎对应于一个列表,因此您需要索引到该列表中以获取dict
例如,
getPageid['results'][0]['id']
应该为“results”
列表中的第一个对象返回“id”
键的字符串值我收到了这个错误,getPageid=json.loads(r)文件“C:\Python27\lib\json\u init.py”,第339行,在loads return\u default\u decoder.decode文件中“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的结果