Updated April 18, 2023
Introduction to Flask jsonify
Flask jsonify is defined as a functionality within Python’s capability to convert a json (JavaScript Object Notation) output into a response object with application/json mimetype by wrapping up a dumps( ) function for adding the enhancements. Along with the conversion of json to an output response, this function helps in conversion of multiple arguments to array or multiple arguments into dictionary. This function comprises of appropriate content type header for ready use by the json responses. There is a significant difference in the json.dumps( ) function and the flask.jsonify( ). Now, let us see at the other components of jsonify, which makes it the most widely used function in flask for json conversion.
Syntax of Flask jsonify
Here we will look at different syntaxes in purview of flask jsonify which are essential for us to glimpse through as this will enable us to know and map the corresponding syntax to the working.
So, here we go with the syntaxes in jsonify:
Importing jsonify in a python code:
from flask import jsonify
Return response object through jsonify:
jsonify(key1=value1 ,
key2=value2 ,
key3=value3)
Difference between jsonify and json.dumps( )
For jsonify:
jsonify(key1=value1 ,
key2=value2 ,
key3=value3)
For json.dumps( ):
Json.dumps(key1=value1 ,
key2=value2 ,
key3=value3)
How does jsonify Work in Flask?
By now we are clear about the purpose of jsonify, that it will be required for conversion of json to response objects.
As we mentioned that jsonify is a wrapper to the dumps( ) function of flask, but it differs from the dumps( ) function in the below following ways:
- During passing single argument, jsonify just passes the parameter as it is to dumps( ) function.
- Before passing multiple arguments, jsonify converts the arguments to array before passing it to dumps( ) function.
- Before passing multiple keyword arguments, jsonify converts the arguments to a dictionary before passing it to dumps( ) function.
- Before passing args and kwargs, jsonify will throw an exception as it is passes to dumps( ) function.
With the latest changes coming in for version 0.11, there is an added support for serializing top-level arrays. This function is loaded directly from the flask module instead of flask.json.
Now let us look at the core working of jsonify function. In order to understand that we need to understand the working of json.dumps( ) as jsonify is just a wrapper over the json.dumps( ) function. Let us say, we receive a HTTP request for extracting detail. The arguments to jsonify function are the same as to the dict constructor. When this request is passed into the dumps( ) function from the jsonify wrapper they are converted by the one best suited out of the above 4 mentioned ways. Now, once the data is retrieved, the data is in form of a python object consisting of one or many arguments. It is then converted into a json formatted string using the functionality of json.dumps( ). In performing the actions, python objects are encoded into json equivalent modules in a standardized format. During this conversion, the function performs the translations while encoding. For example, dict in Python is converted into json object, list or tuple is converted into a json array and so on.
Now once the object is received by the json.dumps( ) function, the wrapper converts the output to a response object with application/json mimetype. This output is generally pretty printed if the HTTP requested is not through using the option of: X-Requested-With: XMLHttpRequest or the parameter JSONIFY_PRETTYPRINT_REGULAR is set to False. Jsonify is incredibly useful in building API that is used by someone who expects the return object to be in json as this might be one of the constraint of the bigger application which uses the API from this flask web application.
Examples of Flask jsonify
Given below are the examples of Flask jsonify:
We would try to look at the major difference which creeps in between using of jsonify and json.dumps( ) function and how the return object looks strikingly different from each other.
Example #1
Importing jsonify in a python code.
Syntax:
from flask import jsonify
jsonify
Output:
Example #2
Return response object through jsonify.
Syntax:
from flask import jsonify, Flask
appFlask = Flask(__name__)
@appFlask.route('/home')
def home():
return jsonify(username='eduCBA' ,
account='Premium' ,
validity='200 days')
if __name__ == "__main__":
appFlask.run(debug=True)
Output:
Example #3
Difference between jsonify and json.dumps( ).
Syntax:
from flask import jsonify, Flask
import json
appFlask = Flask(__name__)
@appFlask.route('/home_jsonify')
def home_jsonify():
Dictionary ={'username':'eduCBA' , 'account':'Premium' , 'validity':'2709 days'}
return jsonify(Dictionary)
@appFlask.route('/home_dumps')
def home_dumps():
Dictionary ={'username':'eduCBA' , 'account':'Premium' , 'validity':'2709 days'}
return json.dumps(Dictionary)
if __name__ == "__main__":
appFlask.run(debug=True)
Output:
jsonify:
dumps:
Here we can clearly notice that the json.dumps( ) returns a string rather than an object that is returned by the jsonify function.
Conclusion
In this article we have got to know about details of how jsonify works in flask application and knowing the full cycle of implementation of jsonify along with some hands-on codes. The next step is to use the concepts in building json return objects for your flask application and thus build a standardized concept which would make your web application consumable by other sources.
Recommended Articles
This is a guide to Flask jsonify. Here we discuss the introduction, how does jsonify work in flask? and examples respectively. You may also have a look at the following articles to learn more –