Sergei Basharov Sergei Basharov - 1 year ago 309
JSON Question

json.dumps vs flask.jsonify

I am not sure I understand the purpose of

method. I try to make json string from this:

data = {"id": str(, "title": album.title}

but what I get with
differs from what I get with

json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business"}]
flask.jsonify(data): {"id", "title"}

Obviously I need to get result that looks more like what
returns. What am I doing wrong?

Answer Source

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.