Open In App

Use jsonify() instead of json.dumps() in Flask

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.




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.




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.




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.




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:


Article Tags :