如何解析来自 Python 请求的 JSON 响应?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26106702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse a JSON response from Python Requests?
提问by horro
I am trying to parse a response.textthat I get when I make a requestusing the Python Requests library. For example:
我试图解析response.text我在request使用 Python 请求库时得到的一个。例如:
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
When I execute this method, the output is:
当我执行这个方法时,输出是:
{"request":"POST /login","result":"success"}
I would like to check whether "result"equals "success", ignoring whatever comes before.
我想检查是否"result"等于"success",忽略之前的任何内容。
采纳答案by AShelly
回答by Clay Benson
Since the output, response, appears to be a dictionary, you should be able to do
由于输出 ,response似乎是一本字典,你应该能够做到
result = self.response.json().get('result')
print(result)
and have it print
并打印
'success'
回答by Anthony Perot
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'
回答by horro
I found another solution. It is not necessary to use jsonmodule. You can create a dictusing dict = eval(whatever)and return, in example, dict["result"]. I think it is more elegant. However, the other solutions also work and are correct
我找到了另一个解决方案。没有必要使用json模块。您可以创建一个dictusingdict = eval(whatever)和 return,例如,dict["result"]. 我认为它更优雅。但是,其他解决方案也有效并且是正确的

