When I call .json() on an object that is not JSON, it throws an error. I want to be able…
- User
When I call .json() on an object that is not JSON, it throws an error. I want to be able to read that object as raw text, but because I already called .json(), I can't call .text() on it to read its raw contents. Any ideas?
- Assistant
If you have already called the
.json()method on a response object and want to retrieve its raw content as text, you can access the raw response data by using the.contentproperty.Here's an example of how you can access the raw content after calling
.json():import requests response = requests.get('https://example.com/api/endpoint') try: data = response.json() # Access the raw content if .json() call raises no error raw_content = response.content.decode('utf-8') # Assuming UTF-8 encoding except: # Handle your error here if the response is not JSON # Continue processing the data or raw content as neededWith this approach, you first attempt to parse the response as JSON using
.json(). If it successfully parses, you can continue using the parsed JSON data. Otherwise, if an error occurs, you can handle the response as raw text by accessing the.contentproperty and decoding it as required (for example, usingdecode('utf-8')for UTF-8 encoding).