The Python Oracle

json.dumps vs flask.jsonify

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
00:37 Accepted answer (Score 442)
01:21 Answer 2 (Score 99)
01:35 Answer 3 (Score 90)
02:07 Answer 4 (Score 52)
02:47 Thank you

--

Full question
https://stackoverflow.com/questions/7907...

Accepted answer links:
[here]: https://flask.palletsprojects.com/api/#f...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #json #flask

#avk47



ACCEPTED ANSWER

Score 447


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.




ANSWER 2

Score 98


You can do:

flask.jsonify(**data)

or

flask.jsonify(id=str(album.id), title=album.title)



ANSWER 3

Score 92


This is flask.jsonify()

def jsonify(*args, **kwargs):
    if __debug__:
        _assert_have_json()
    return current_app.response_class(json.dumps(dict(*args, **kwargs),
        indent=None if request.is_xhr else 2), mimetype='application/json')

The json module used is either simplejson or json in that order. current_app is a reference to the Flask() object i.e. your application. response_class() is a reference to the Response() class.




ANSWER 4

Score 54


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.