Sergei Basharov Sergei Basharov - 4 months ago 72
JSON Question

json.dumps vs flask.jsonify

I am not sure I understand the purpose of

flask.jsonify
method. I try to make 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 result that looks more like what
json.dumps
returns. What am I doing wrong?

Answer

The jsonify() function in flask returns flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses, whereas the json.dumps() 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.

Comments