Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a JSON response from Python Requests?

Tags:

I am trying to parse a response.text that I get when I make a request using the Python Requests library. For example:

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.

like image 995
horro Avatar asked Sep 29 '14 18:09

horro


People also ask

How do you parse a JSON value in Python?

Parse JSON - Convert from JSON to Python If you have a JSON string, you can parse it by using the json. loads() method. The result will be a Python dictionary.


1 Answers

The manual suggests: if self.response.status_code == requests.codes.ok:

If that doesn't work:

if json.loads(self.response.text)['result'] == 'success':
   whatever()
like image 158
AShelly Avatar answered Oct 05 '22 07:10

AShelly