Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read python flask jsonify response object

Tags:

python

json

flask

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

like image 344
user2916886 Avatar asked Mar 06 '23 17:03

user2916886


1 Answers

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"))
    # ...
like image 177
Matthew Story Avatar answered Mar 12 '23 17:03

Matthew Story