我正在尝试解析当我使用Python Requests库创建response.text
时得到的request
。例如:
def check_user(self):
method = 'POST'
url = 'http://localhost:5000/login'
ck = cookielib.CookieJar()
self.response = requests.request(method,url,data='username=test1&passwd=pass1', cookies=ck)
print self.response.text
执行此方法时,输出为:
{"request":"POST /login","result":"success"}
我想检查"result"
是否等于"success"
,忽略之前发生的事情。
答案 0 :(得分:12)
manual建议:if self.response.status_code == requests.codes.ok:
如果不起作用:
if json.loads(self.response.text)['result'] == 'success':
whatever()
答案 1 :(得分:4)
由于输出response
似乎是字典,您应该可以
result = self.response.json().get('result')
print(result)
并打印
'success'
答案 2 :(得分:1)
import json
def check_user(self):
method = 'POST'
url = 'http://localhost:5000/login'
ck = cookielib.CookieJar()
response = requests.request(method,url,data='username=test1&passwd=pass1', cookies=ck)
#this line converts the response to a python dict which can then be parsed easily
response_native = json.loads(response.text)
return self.response_native.get('result') == 'success'
答案 3 :(得分:1)
我找到了另一个解决方案。没有必要使用json
模块。您可以使用dict
创建dict = eval(whatever)
,然后返回dict["result"]
。我认为它更优雅。但是,其他解决方案也可以正常使用
答案 4 :(得分:0)
像这样将方法返回:
return self.response.json()
如果您想查找更多详细信息,请单击以下链接: https://www.w3schools.com/python/ref_requests_response.asp
并搜索json()方法。
这是一个代码示例:
import requests
url = 'https://www.w3schools.com/python/demopage.js'
x = requests.get(url)
print(x.json())
答案 5 :(得分:0)
如果响应位于json中,则可以执行类似(python3)的操作:
import json
import requests as reqs
# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
要查看响应中的所有内容,可以使用.__dict__
:
print(response.__dict__)
答案 6 :(得分:0)
在某些情况下,响应可能会是预期的。因此,如果我们可以构建一种机制来捕获和记录异常,那就太好了。
import requests
import sys
url = "https://stackoverflow.com/questions/26106702/how-do-i-parse-a-json-response-from-python-requests"
response = requests.get(url)
try:
json_data = response.json()
except ValueError as exc:
print(f"Exception: {exc}")
# to find out why you have got this exception, you can see the response content and header
print(str(response.content))
print(str(response.headers))
print(sys.exc_info())
else:
if json_data.get('result') == "success":
# do whatever you want
pass