I have a python
function which returns Flask jsonify
object. When I try to read this returned json
object using get_json()
or even json()
it throws error. Here is my code:
from flask import jsonify
def funct1(par1):
if par1 == 'Hi':
return jsonify(result=1,msg='Hello')
else:
return jsonify(result=0,msg='Sorry')
def func2():
response = funct1('Hi')
rsp_js = response.get_json() # This throws error
print(rsp_js)
When I execute above I get error as Response object has no attribute get_json
. I tried json()
as well but get the same error. How can I read the returned jsonify object?
NOTE: I have flask version 0.12.2
get_json
was not added to response objects in flask until version 1.0. In previous versions, you need to use get_data
:
import json
json.loads(response.get_data().decode("utf-8"))
Having said this, I would caution you against calling route methods directly from other functions (except for testing), or returning response objects from non-route methods.
If you are attempting to test this method, you should consider using the test_client
:
with app.test_client() as client:
json.loads(client.get("the/url").get_data().decode("utf-8"))
# ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With