AttributeError: ‘Response’ object has no attribute ‘json’

Loading

The error “AttributeError: ‘Response’ object has no attribute ‘json'” occurs when you try to access the .json() method on an object that does not support it. This usually happens when using an incorrect library or a different type of response object.


Common Causes and Fixes

1. Using Flask’s Response Instead of requests.Response

If you’re working with Flask and trying to parse JSON from a response, note that Flask’s Response object does not have a .json() method.

Incorrect Flask Example:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/data')
def get_data():
response = jsonify({"message": "Hello"})
print(response.json()) # AttributeError
return response

Fix: Use .get_json() instead of .json()

@app.route('/data')
def get_data():
response = jsonify({"message": "Hello"})
print(response.get_json()) # Correct
return response

2. Using the requests Library but Getting an Unexpected Response

If you’re working with requests.get(), ensure you’re calling .json() on a valid requests.Response object.

Incorrect Example:

import requests

response = requests.get("https://example.com")
response = response.text # This makes response a string
data = response.json() # AttributeError

Fix: Call .json() on the original response object.

import requests

response = requests.get("https://example.com")
data = response.json() # Correct
print(data)

3. The Response is Not in JSON Format

If the API response is not JSON (e.g., plain text or HTML), calling .json() will fail.

Fix: Check the response type before calling .json()

import requests

response = requests.get("https://example.com")

try:
data = response.json()
except requests.exceptions.JSONDecodeError:
print("Response is not JSON")
data = response.text # Fallback to text

print(data)

4. Ensure You Are Using the requests Library

If you mistakenly use Flask’s Response instead of requests.Response, you might get this error.

Incorrect Flask Response Parsing:

from flask import Response
response = Response("Hello, World!")
print(response.json()) # AttributeError

Fix: Convert the response manually.

import json
from flask import Response

response = Response(json.dumps({"message": "Hello"}), content_type="application/json")
print(json.loads(response.data)) # Correct

Summary of Fixes

IssueFix
Flask Response has no .json() methodUse .get_json() instead
Calling .json() on response.textUse .json() on requests.Response object directly
API response is not JSONUse try-except for requests.exceptions.JSONDecodeError
Flask’s Response needs parsingUse json.loads(response.data)

Leave a Reply

Your email address will not be published. Required fields are marked *