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?
jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data. This could lead to unintended results.
In the conditional, Flask checks if the body is of type dict and if so calls jsonify . To see this in action refer to the previously mentioned line in the core Flask app.py . So, while we no longer need to explicitly call jsonify it is still very much being used by the application itself.
jsonify is a function in Flask's flask. json module. jsonify serializes data to JavaScript Object Notation (JSON) format, wraps it in a Response object with the application/json mimetype. Note that jsonify is sometimes imported directly from the flask module instead of from flask.
json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.
The jsonify()
function in flask returns a flask.Response()
object that already has the appropriate content-type header 'application/json' for use with json responses. Whereas, the json.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, while json.dumps()
additionally supports lists and others.
You can do:
flask.jsonify(**data)
or
flask.jsonify(id=str(album.id), title=album.title)
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