return json in flask in python

To return JSON in Flask, first you need to import the jsonify function from the flask module. jsonify takes a Python dictionary and returns a JSON response to the client.

Here's an example code snippet to return a JSON response:

main.py
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/data')
def get_data():
    data = {'name': 'John', 'age': 30, 'city': 'New York'}
    # use jsonify to return a JSON response
    return jsonify(data)

if __name__ == '__main__':
    app.run()
263 chars
13 lines

In this example, we define a simple Flask route named /data which returns a dictionary as a JSON response to the client. The jsonify function ensures that the response is properly formatted as JSON.

When we run the Flask application and visit the /data endpoint in our browser, we should see the following JSON response:

{
  "name": "John",
  "age": 30,
  "city": "New York"
}
56 chars
6 lines

gistlibby LogSnag