jsonify() vs json.dumps() in Flask

In this tutorial, we will learn the difference between jsonify() vs json.dumps() in Flask in Python

jsonify()

  • The jsonify() function belongs from Flask framework.
  • The jsonify() is used to convert a JSON (JavaScript Object Notation) response into a flask.response object(which is directly compatible with the flask framework) with setting mimetype header field as application/json.
  • This function configures the correct response headers and other fields for JSON responses by its own.
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/')
def index():
    return jsonify(name='Anuj' ,company='Codespeedy' ,role='Python Developer')

if __name__ == '__main__':
    app.run()

Output

{"company":"Codespeedy", "name":"Anuj", "role":"Python Developer"}

json.dumps()

  • json.dumps() is from JSON package which is a python built-in package.
  • In this firstly you must convert the data into JSON format, and then have to manually set the response headers.
  • This function converts Python datatypes(such as dictionaries, lists etc.) into JSON string.
import json
students = [
  {'name': 'Alina', 'rollno':'1'},
  {'name': 'Jack', 'author': '2'}
]
print(json.dumps(students))

Output

[{"name": "Alina", "rollno": "1"}, {"name": "Jack", "author": "2"}]

Conclusion

Here we can see that the json.dumps( ) returns a string whereas jsonify() function returns an object. And hence it is preferable to use jsonify() while building flask applications.

We’ve successfully learned the difference between jsonify() vs json.dumps() in Python, simplifying the solution for better comprehension. I hope you found this tutorial informative!

Leave a Reply

Your email address will not be published. Required fields are marked *