flask import jsonify
To use the jsonify
function in Flask, you need to import it from the Flask module. The jsonify
function is used to convert a Python dictionary or list into a JSON response.
Here are the steps to import and use jsonify
in Flask:
- Import the
jsonify
function from the Flask module by adding the following line at the top of your Python file:
from flask import jsonify
- Create a dictionary or list that you want to convert to JSON. For example:
data = {
'name': 'John',
'age': 30,
'city': 'New York'
}
- Use the
jsonify
function to convert the data into a JSON response. For example:
json_response = jsonify(data)
- You can then return the JSON response from a Flask route or endpoint. For example:
@app.route('/data')
def get_data():
return json_response
This will return a JSON response containing the data in the specified route.
That's it! You have successfully imported and used the jsonify
function in Flask to convert data into a JSON response.