Open In App

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

Last Updated : 22 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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

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

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

 

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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads