Flask JSON
Flask's JSON module provides serialization/deserialization functionality. By default it uses Python's standard json library under the hood, which can be replaced via JSONProvider.
Import method:
from flask import jsonify
or
from flask.json import dumps, loads
The jsonify Function
The most commonly used JSON response building function. Serializes Python objects into a JSON Response.
| Usage | Description |
|---|---|
| jsonify(*args, **kwargs) | Serializes arguments into JSON and returns a Response (Content-Type: application/json) |
| jsonify(dict) | Serialize a dictionary into a JSON response |
| jsonify(key=value, ...) | Serialize keyword arguments into a JSON response |
dumps / loads / dump / load
| function | Signing | Description |
|---|---|---|
| dumps | (obj, *, skipkeys=False, ensure_ascii=True, ...) | Serialize a Python object into a JSON string |
| loads | (s, *, ...) | Deserialize a JSON string into a Python object |
| dump | (obj, fp, *, ...) | Serialize a Python object and write it to a file |
| load | (fp, *, ...) | Read from a file and deserialize JSON |
The JSONProvider Class
A customizable base class for JSON handling. To replace the default JSON implementation, inherit from this class and override the relevant methods.
| Method | Description |
|---|---|
| dumps(obj, **kwargs) | Serialize an object into a JSON string |
| loads(s, **kwargs) | Deserialize a JSON string into a Python object |
| response(obj) | Convert an object into a JSON Response. Used by jsonify and when returning dict/list |
DefaultJSONProvider
The default JSONProvider implementation, based on Python's standard json library.
| Attribute / method | 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 (no spaces). Defaults to False |
JSON Tag Serialization
The flask.json.tag module supports serializing more Python types, such as datetime, tuple, set, and so on.
| tag | Corresponding Python Type |
|---|---|
| JSONTaggedJSONSerializer | An enhanced serializer used by Session by default. Supports tagged JSON format |
Code Example
Example
from
flask
import
Flask
,
jsonify
app
=
Flask
(
name
)
@
app.
get
(
"/api/me"
)
def
me
(
)
:
Return a dict, and Flask automatically calls jsonify
return
{
"username"
:
"runoob"
,
"email"
:
"test@runoob.com"
,
"roles"
:
[
"admin"
,
"editor"
]
}
@
app.
get
(
"/api/users"
)
def
users
(
)
:
Return a list, and Flask automatically calls jsonify
return
[
{
"id"
:
1
,
"name"
:
"runoob"
}
,
{
"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