JSON is a data-interchange format like xml does. It is easy for humans to read and write, and it is also easy for machines to parse and generate. Flask framework provides a simple way to send JSON data.
Step 1: Create a folder containing the data you want to send.
For example, the following dictionary contains the name, age, and city of a person:
data = {
"name": "John",
"age": 30,
"city": "New York"
}
Step 2: Use the jsonify() function provided by Flask to convert the data to JSON format and send it as a response.
The json.dumps function takes a dictionary as its argument and returns a response object with the JSON representation of the dictionary. For example, the following code sends the JSON data in the data dictionary as a response:
from flask import Flask, json
app = Flask(__name__)
@app.route('/json')
def send_json():
data = {
"name": "John",
"age": 30,
"city": "New York"
}
return json.dumps(data)
if __name__ == '__main__':
app.run()
Step 3: Test the application.
You can test the application by opening a web browser.
If the application is working correctly, you should see the JSON data in the web browser.
Here is an example of the JSON data that you should see:
{
"name": "John",
"age": 30,
"city": "New York"
}
Work with our skilled Python developers to accelerate your project and boost its performance.
Hire Python Developers