I am not sure I understand the purpose of the flask.jsonify
method. I try to make a JSON string from this:
data = {"id": str(album.id), "title": album.title}
but what I get with json.dumps
differs from what I get with flask.jsonify
.
json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business"}]
flask.jsonify(data): {"id":…, "title":…}
Obviously I need to get a result that looks more like what json.dumps
returns. What am I doing wrong?
The choice of one or another depends on what you intend to do. From what I do understand:
jsonify would be useful when you are building an API someone would query and expect json in return. E.g: The REST github API could use this method to answer your request.
dumps, is more about formating data/python object into json and work on it inside your application. For instance, I need to pass an object to my representation layer where some javascript will display graph. You'll feed javascript with the Json generated by dumps.
This is
flask.jsonify()
The
json
module used is eithersimplejson
orjson
in that order.current_app
is a reference to theFlask()
object i.e. your application.response_class()
is a reference to theResponse()
class.You can do:
or
The
jsonify()
function in flask returns aflask.Response()
object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, thejson.dumps()
method will just return an encoded string, which would require manually adding the MIME type header.See more about the
jsonify()
function here for full reference.Edit: Also, I've noticed that
jsonify()
handles kwargs or dictionaries, whilejson.dumps()
additionally supports lists and others.