Problem
I’m not sure I understand the flask’s function. jsonify is a technique that converts a string into a j I try to convert this to a JSON string:
data = {"id": str(album.id), "title": album.title}
However, what I receive with json.dumps is not the same as what I get with flask. jsonify.
json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business"}]
flask.jsonify(data): {"id":…, "title":…}
Obviously, I need a result that resembles the output of json.dumps. What am I doing incorrectly?
Asked by Sergei Basharov
Solution #1
The flask jsonify() function returns a flask. For use with json responses, utilize a Response() object that already has the necessary content-type header ‘application/json’. The json.dumps() function, on the other hand, will just return an encoded text, requiring the MIME type header to be manually added.
See more about the jsonify() function here for full reference.
Edit: I’ve also found that jsonify() can use kwargs or dictionaries, whereas json.dumps() can also handle lists and other data types.
Answered by Kenneth Wilke
Solution #2
You can do:
flask.jsonify(**data)
or
flask.jsonify(id=str(album.id), title=album.title)
Answered by mikerobi
Solution #3
This is flask.jsonify()
def jsonify(*args, **kwargs):
if __debug__:
_assert_have_json()
return current_app.response_class(json.dumps(dict(*args, **kwargs),
indent=None if request.is_xhr else 2), mimetype='application/json')
In that sequence, the json module used is either simplejson or json. current app is a reference to your application’s Flask() object. response_class() is a reference to the Response() class.
Answered by Michael Ekoka
Solution #4
The decision between the two is based on your objectives. From what I’ve gathered:
Answered by chaiyachaiya
Solution #5
consider
data={'fld':'hello'}
now
jsonify(data)
will return ‘fld’:’hello’ and
json.dumps(data)
gives
"<html><body><p>{'fld':'hello'}</p></body></html>"
Answered by Govind Kelkar
Post is based on https://stackoverflow.com/questions/7907596/json-dumps-vs-flask-jsonify