How do I parse a JSON response from Python Requests?

后端 未结 7 1219
悲&欢浪女
悲&欢浪女 2021-02-19 00:09

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(s         


        
相关标签:
7条回答
  • 2021-02-19 00:34
        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'
    
    0 讨论(0)
  • 2021-02-19 00:36

    Put in the return of your method like this:

    return self.response.json()

    If you wanna looking for more details, click this following link: https://www.w3schools.com/python/ref_requests_response.asp

    and search for json() method.

    Here is an code example:

    import requests
    url = 'https://www.w3schools.com/python/demopage.js'
    x = requests.get(url)
    print(x.json())
    
    0 讨论(0)
  • 2021-02-19 00:37

    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()
    
    0 讨论(0)
  • 2021-02-19 00:43

    If the response is in json you could do something like (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])
    

    To see everything in the response you can use .__dict__:

    print(response.__dict__)
    
    0 讨论(0)
  • 2021-02-19 00:45

    Since the output, response, appears to be a dictionary, you should be able to do

    result = self.response.json().get('result')
    print(result)
    

    and have it print

    'success'
    
    0 讨论(0)
  • 2021-02-19 00:46

    In some cases, maybe the response would be as expected. So It'd be great if we can built a mechanism to catch and log the exception.

    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
    
    0 讨论(0)
提交回复
热议问题