Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.dumps vs flask.jsonify

Tags:

python

json

flask

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?

like image 918
Sergei Basharov Avatar asked Oct 26 '11 19:10

Sergei Basharov


People also ask

What is the difference between Jsonify and json dumps?

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.

Do you need Jsonify in Flask?

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.

What does Jsonify do in Flask?

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.

What is the difference between json dump and json dumps?

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.


2 Answers

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.

like image 176
Kenneth Wilke Avatar answered Oct 06 '22 06:10

Kenneth Wilke


You can do:

flask.jsonify(**data) 

or

flask.jsonify(id=str(album.id), title=album.title) 
like image 33
mikerobi Avatar answered Oct 06 '22 06:10

mikerobi