Flask JSON
Flask's JSON module provides serialization/deserialization functionality, using Python's standard library json by default underneath, which can be replaced via JSONProvider.
Import method:
from flask import jsonify
or
from flask.json import dumps, loads
jsonify function
The most commonly used JSON response construction function. Serializes Python objects into a JSON Response.
| Usage | Description |
|---|---|
| jsonify(*args, **kwargs) | Serialize parameters to JSON, return Response (Content-Type: application/json) |
| jsonify(dict) | Serialize dictionary to JSON response |
| jsonify(key=value, ...) | Serializes keyword arguments into a JSON response |
dumps / loads / dump / load
| Function | Signature | Description |
|---|---|---|
| dumps | (obj, *, skipkeys=False, ensure_ascii=True, ...) | Serializes Python objects into a JSON string |
| loads | (s, *, ...) | Deserializes a JSON string into a Python object |
| dump | (obj, fp, *, ...) | Serializes a Python object and writes it to a file |
| load | (fp, *, ...) | Reads from a file and deserializes JSON |
JSONProvider class
Customizable JSON handler base class. To replace the default JSON implementation, inherit this class and override the relevant methods.
| Methods | Description |
|---|---|
| dumps(obj, **kwargs) | Serializes an object into a JSON string |
| loads(s, **kwargs) | Deserializes from a JSON string into a Python object |
| response(obj) | Convert the object to a JSON Response. Used for jsonify and when returning dict/list. |
DefaultJSONProvider
The default JSONProvider implementation, based on the Python standard library json.
| Attributes/Methods | Description |
|---|---|
| ensure_ascii | Whether to escape non-ASCII characters. Can be set to False to support Chinese output |
| sort_keys | Whether to sort output by key. Defaults to True |
| compact | Whether to output compactly (without spaces). Defaults to False |
JSON Tag Serialization
flask.json.tagThe module supports serializing more Python types, such as datetime, tuple, set, etc.
| Tags | Corresponding Python types |
|---|---|
| JSONTaggedJSONSerializer | Enhanced serializer, used by Session by default. Supports tagged JSON format |
Code Examples
Example
from flask import Flask, jsonify
app = Flask(__name__)
@app.get("/api/me")
def me():
# Return dict, Flask automatically calls jsonify
return {
"username": "example",
"email": "test@example.com",
"roles": ["admin", "editor"]
}
@app.get("/api/users")
def users():
# Return list, Flask automatically calls jsonify
return [
{"id": 1, "name": "example"},
{"id": 2, "name": "admin"}
]
@app.get("/api/status")
def status():
# Explicitly use jsonify
return jsonify(status="ok", version="1.0")
# Configure Chinese JSON output
app.json.ensure_ascii = False
# {"username": "example", "description": "Chinese description content"}
app = Flask(__name__)
@app.get("/api/me")
def me():
# Return dict, Flask automatically calls jsonify
return {
"username": "example",
"email": "test@example.com",
"roles": ["admin", "editor"]
}
@app.get("/api/users")
def users():
# Return list, Flask automatically calls jsonify
return [
{"id": 1, "name": "example"},
{"id": 2, "name": "admin"}
]
@app.get("/api/status")
def status():
# Explicitly use jsonify
return jsonify(status="ok", version="1.0")
# Configure Chinese JSON output
app.json.ensure_ascii = False
# {"username": "example", "description": "Chinese description content"}