Use jsonify() instead of json.dumps() in Flask
Last Updated :
26 Apr, 2025
Here, we will understand the jsonify() function in the Flask web framework for Python that converts the output of a function to a JSON response object. It is similar to the json.dumps() function in the Python standard library, which converts a Python object to a JSON-formatted string.
What is jsonify()
The jsonify() function is useful in Flask apps because it automatically sets the correct response headers and content type for JSON responses, and allows you to easily return JSON-formatted data from your route handlers. This makes it easier and more convenient to create APIs that return JSON data.
Syntax of jsonify() function
This function takes in one or more positional arguments, which represent the data to be converted to a JSON response object, and any number of keyword arguments, which are used to customize the JSON response object.
jsonify(*args, **kwargs)
Example of jsonify() with without argument
You can use jsonify() without any arguments, in this case it will return an empty JSON response object with a default status code of 200 (OK) and a default content type of application/json.
Python3
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/users')
def get_users():
return jsonify()
Example of jsonify() with arguments
In this example, we are calling jsonify() with a single positional argument (the list of user objects), as well as two keyword arguments with status and mimetype. The status argument is used to set the HTTP status code for the response, and the mimetype argument is used to set the content type for the response.
Python3
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/api/users')
def get_users():
users = [{'id': 1, 'username': 'Alice'}, {'id': 2, 'username': 'Bob'}]
return jsonify(users, status=200, mimetype='application/json')
jsonify() method in Flask
In this example, we have a Flask app with a route that returns a list of user objects. When a client makes a request to this route, the get_users() function is executed and the list of user objects is converted to a JSON response object using the jsonify() function. This JSON response object is then sent back to the client.
Python3
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def get_users():
print("Using jsonify")
users = [{'id': 1, 'username': 'sweety'},
{'id': 2, 'username': 'pallavi'}]
return jsonify({'users': users})
if __name__ == '__main__':
app.run()
Output:
jsonify() method json.dumps() method in Flask
In contrast, if you were to use the json.dumps() function, you would need to convert the list of user objects to a JSON-formatted string yourself, and then set the appropriate response headers and return the response to the client manually:
Using jsonify() is generally easier and more convenient than using json.dumps(), so it's recommended to use jsonify() whenever possible in Flask apps.
Python3
from flask import Flask, Response
import json
app = Flask(__name__)
@app.route('/api/users')
def get_users():
users = [{'id': 1, 'username': 'sweety'},
{'id': 2, 'username': 'pandey'}]
response = Response(
response=json.dumps(users),
status=200,
mimetype='application/json'
)
return response
if __name__ == "__main__":
app.run()
Output:
http://127.0.0.1:5000/api/users
Why to Use jsonify() instead of json.dumps()
There are several reasons why it is recommended to use the jsonify() function instead of the json.dumps() function in Flask apps:
- The jsonify() is more convenient and easier to use than json.dumps(). jsonify() has a simple and intuitive syntax, and it automatically handles the details of converting your data to a JSON response object and returning it to the client. In contrast, json.dumps() requires you to handle these details yourself, which can be more time-consuming and error-prone.
- The jsonify() automatically sets the correct response headers and content type for JSON responses, while json.dumps() does not. This means that you don't have to manually set the Content-Type header to application/json when using jsonify(), but you would have to do so manually when using json.dumps().
- jsonify() allows you to easily return JSON-formatted data from your route handlers, while json.dumps() does not. With jsonify(), you can simply return the data that you want to be converted to a JSON response object from your route handler, and jsonify() will take care of the rest. With json.dumps(), you would have to convert the data to a JSON-formatted string yourself and then return it as part of a Response object.
- Overall, using jsonify() instead of json.dumps() in Flask apps can make it easier and more convenient to create APIs that return JSON data. It allows you to focus on the data and logic of your app, rather than having to worry about the details of formatting and returning JSON responses.
Similar Reads
How to use Flask-Session in Python Flask
Sessions in Flask store user-specific data across requests, like login status, using cookies. Data is stored on the client side but signed with a secret key to ensure security. They help maintain user sessions without requiring constant authentication.This article demonstrates how to implement serve
4 min read
How to Install Flask-CORS in Python
In this article, we will learn to install Flask-CORS which is a Python module and a Flask extension that supports and allows cross-origin resource sharing (CORS) through a simple decorator. Due to security concerns, cross-domain cookie submission is disabled by default. We will look at how to instal
3 min read
Todo list app using Flask | Python
There are many frameworks that allow building your webpage using Python, like Django, flask, etc. Flask is a web application framework written in Python. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. Its modules and libraries that help the developer to writ
3 min read
Passing URL Arguments in Flask
In this article, we will cover how to Pass URL Arguments in Flask using Python. URL converters in Flask are mentioned in angular brackets (<>). These unique converters are designed to let us generate extremely dynamic URLs, where a part of the URL is regarded as a variable. For that we have cr
4 min read
Read File Without Saving in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article we will discuss how can we Read fil
2 min read
Build Your Own Microservices in Flask
Nowadays Python is everywhere. This is majorly due to its simplicity and wide range of applications. Flask is a lightweight web framework for building web applications in Python. Creating microservices with Flask is straightforward. In this article, we will start with a basic "hello world" microserv
5 min read
json.dumps() in Python
JSON is an acronym that stands for JavaScript Object Notation. Despite its name, JSON is a language agnostic format that is most commonly used to transmit data between systems, and on occasion, store data. Programs written in Python, as well as many other programming languages, can ingest JSON forma
6 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster a
12 min read
Psycopg2 - Insert dictionary as JSON
In this article, we are going to see how to insert a dictionary as JSON using Psycopg2 and Python. Python dict objects can be or rather should be stored in database tables as JSON datatype. Since most of the SQL databases have a JSON datatype. This allows using these objects or key-value pairs in th
4 min read
Append to JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
2 min read