How do I parse a JSON response from Python Requests?

后端 未结 7 1224
悲&欢浪女
悲&欢浪女 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: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
    

提交回复
热议问题