JSON Support โ
Flask uses Pythonโs built-in json module for handling JSON by default. The JSON implementation can be changed by assigning a different provider to flask.Flask.json_provider_class or flask.Flask.json. The functions provided by flask.json will use methods on app.json if an app context is active.
Jinjaโs |tojson filter is configured to use the appโs JSON provider. The filter marks the output with |safe. Use it to render data inside HTML <script> tags.
<script>
const names = {{ names|tojson }};
renderChart(names, {{ axis_data|tojson }});
</script><script>
const names = {{ names|tojson }};
renderChart(names, {{ axis_data|tojson }});
</script>flask.json.jsonify(*args, **kwargs) โ
Serialize the given arguments as JSON, and return a Response object with the application/json mimetype. A dict or list returned from a view will be converted to a JSON response automatically without needing to call this.
This requires an active request or application context, and calls app.json.response().
In debug mode, the output is formatted with indentation to make it easier to read. This may also be controlled by the provider.
Either positional or keyword arguments can be given, not both. If no arguments are given, None is serialized.
Parameters:
args (t.Any)โ A single value to serialize, or multiple values to treat as a list to serialize.kwargs (t.Any)โ Treat as a dict to serialize.
Return type: Response
Changelog
Changed in version 2.2: Calls current_app.json.response, allowing an app to override the behavior.
Changed in version 2.0.2: decimal.Decimal is supported by converting to a string.
Changed in version 0.11: Added support for serializing top-level arrays. This was a security risk in ancient browsers. See JSON Security.
New in version 0.2.
flask.json.dumps(obj, **kwargs) โ
Serialize data as JSON.
If current_app is available, it will use its app.json.dumps() method, otherwise it will use json.dumps().
Parameters:
obj (Any)โ The data to serialize.kwargs (Any) โ Arguments passed to the dumps implementation.
Return type: str
Changed in version 2.3: The app parameter was removed.
Changelog
Changed in version 2.2: Calls current_app.json.dumps, allowing an app to override the behavior.
Changed in version 2.0.2: decimal.Decimal is supported by converting to a string.
Changed in version 2.0: encoding will be removed in Flask 2.1.
Changed in version 1.0.3: app can be passed directly, rather than requiring an app context for configuration.
flask.json.dump(obj, fp, **kwargs) โ
Serialize data as JSON and write to a file.
If current_app is available, it will use its app.json.dump() method, otherwise it will use json.dump().
Parameters:
obj (Any)โ The data to serialize.fp (IO[str])โ A file opened for writing text. Should use theUTF-8encoding to be validJSON.kwargs (Any)โ Arguments passed to the dump implementation.
Return type: None
Changed in version 2.3: The app parameter was removed.
Changelog
Changed in version 2.2: Calls current_app.json.dump, allowing an app to override the behavior.
Changed in version 2.0: Writing to a binary file, and the encoding argument, will be removed in Flask 2.1.
flask.json.loads(s, **kwargs) โ
Deserialize data as JSON.
If current_app is available, it will use its app.json.loads() method, otherwise it will use json.loads().
Parameters:
s (str | bytes)โ Text orUTF-8bytes.kwargs (Any)โ Arguments passed to the loads implementation.
Return type: Any
Changed in version 2.3: The app parameter was removed.
Changelog
Changed in version 2.2: Calls current_app.json.loads, allowing an app to override the behavior.
Changed in version 2.0: encoding will be removed in Flask 2.1. The data must be a string or UTF-8 bytes.
Changed in version 1.0.3: app can be passed directly, rather than requiring an app context for configuration.
flask.json.load(fp, **kwargs) โ
Deserialize data as JSON read from a file.
If current_app is available, it will use its app.json.load() method, otherwise it will use json.load().
Parameters:
fp (IO)โ A file opened for reading text orUTF-8bytes.kwargs (Any)โ Arguments passed to the load implementation.
Return type: Any
Changed in version 2.3: The app parameter was removed.
Changelog
Changed in version 2.2: Calls current_app.json.load, allowing an app to override the behavior.
Changed in version 2.2: The app parameter will be removed in Flask 2.3.
Changed in version 2.0: encoding will be removed in Flask 2.1. The file must be text mode, or binary mode with UTF-8 bytes.
class flask.json.provider.JSONProvider(app) โ
A standard set of JSON operations for an application. Subclasses of this can be used to customize JSON behavior or use different JSON libraries.
To implement a provider for a specific library, subclass this base class and implement at least dumps() and loads(). All other methods have default implementations.
To use a different provider, either subclass Flask and set json_provider_class to a provider class, or set app.json to an instance of the class.
Parameters:
app (Flask)โ An application instance. This will be stored as aweakref.proxyon the_appattribute.
Changelog
New in version 2.2.
dumps(
obj, **kwargs) โSerialize data as
JSON.Parameters:
obj (Any)โ The data to serialize.kwargs (Any)โ May be passed to the underlying JSON library.
Return type:
strdump(obj, fp, **kwargs) โ
Serialize data as JSON and write to a file.
Parameters:
obj (Any)โ The data to serialize.fp (IO[str])โ A file opened for writing text. Should use theUTF-8encoding to be valid JSON.kwargs (Any)โ May be passed to the underlying JSON library.
Return type:
Noneloads(
s, **kwargs) โDeserialize data as JSON.
Parameters:
s (str | bytes)โ Text orUTF-8bytes.kwargs (Any)โ May be passed to the underlying JSON library.
Return type:
Anyload(
fp, **kwargs) โDeserialize data as
JSONread from a file.Parameters:
fp (IO)โ A file opened for reading text or UTF-8 bytes.kwargs (Any)โ May be passed to the underlying JSON library.Return type:
Anyresponse(
*args, **kwargs) โSerialize the given arguments as JSON, and return a
Responseobject with theapplication/jsonmimetype.The
jsonify()function calls this method for the current application.Either positional or keyword arguments can be given, not both. If no arguments are given,
Noneis serialized.Parameters:
args (t.Any)โ A single value to serialize, or multiple values to treat as a list to serialize.kwargs (t.Any)โ Treat as a dict to serialize.Return type:
Response
class flask.json.provider.DefaultJSONProvider(app) โ
Provide JSON operations using Pythonโs built-in json library. Serializes the following additional data types:
datetime.datetimeanddatetime.dateare serialized toRFC 822strings. This is the same as theHTTPdate format.uuid.UUIDis serialized to a string.dataclasses.dataclassis passed todataclasses.asdict().Markup(or any object with a__html__method) will call the__html__method to get a string.
Parameters:
app (Flask)โ
staticdefault(o) โApply this function to any object that
json.dumps()does not know how to serialize. It should return a validJSONtype or raise aTypeError.Parameters:
o (Any)โ
Return type:
Anyensure_ascii =
TrueโReplace non-ASCII characters with escape sequences. This may be more compatible with some clients, but can be disabled for better performance and size.
sort_keys =
TrueโSort the keys in any serialized dicts. This may be useful for some caching situations, but can be disabled for better performance. When enabled, keys must all be strings, they are not converted before sorting.
compact:
bool | None = NoneโIf
True, orNoneout of debug mode, theresponse()output will not add indentation, newlines, or spaces. IfFalse, orNonein debug mode, it will use a non-compact representation.mimetype =
'application/json'โThe mimetype set in
response().dumps(
obj, **kwargs) โSerialize data as
JSONto a string.Keyword arguments are passed to
json.dumps(). Sets some parameter defaults from the default,ensure_ascii, andsort_keysattributes.Parameters:
obj (Any)โ The data to serialize.kwargs (Any)โ Passed to json.dumps().
Return type:
strloads(
s, **kwargs) โDeserialize data as
JSONfrom a string or bytes.Parameters:
s (str | bytes)โ Text orUTF-8bytes.kwargs (Any)โ Passed tojson.loads().
Return type:
Anyresponse(
*args, **kwargs) โSerialize the given arguments as
JSON, and return aResponseobject with it. The response mimetype will beโapplication/jsonโand can be changed withmimetype.If compact is
Falseor debug mode is enabled, the output will be formatted to be easier to read.Either positional or keyword arguments can be given, not both. If no arguments are given,
Noneis serialized.Parameters:
args (t.Any)โ A single value to serialize, or multiple values to treat as a list to serialize.kwargs (t.Any)โ Treat as a dict to serialize.
Return type:
Response
Tagged JSON โ
A compact representation for lossless serialization of non-standard JSON types. SecureCookieSessionInterface uses this to serialize the session data, but it may be useful in other places. It can be extended to support other types.
class flask.json.tag.TaggedJSONSerializer โ
Serializer that uses a tag system to compactly represent objects that are not JSON types. Passed as the intermediate serializer to itsdangerous.Serializer.
The following extra types are supported:
dicttuplebytesMarkupUUIDdatetime
default_tags =
[<class 'flask.json.tag.TagDict'>, <class 'flask.json.tag.PassDict'>, <class 'flask.json.tag.TagTuple'>, <class 'flask.json.tag.PassList'>, <class 'flask.json.tag.TagBytes'>, <class 'flask.json.tag.TagMarkup'>, <class 'flask.json.tag.TagUUID'>, <class 'flask.json.tag.TagDateTime'>]โTag classes to bind when creating the serializer. Other tags can be added later using
register().dumps(
value) โTag the value and dump it to a compact
JSONstring.Parameters:
value (Any)โ
Return type:
strloads(
value) โLoad data from a
JSONstring and deserialized any tagged objects.Parameters:
value (str)โ
Return type:
Anyregister(
tag_class, force=False, index=None) โRegister a new tag with this serializer.
Parameters:
tag_class (type[flask.json.tag.JSONTag])โ tag class to register. Will be instantiated with this serializer instance.force (bool)โ overwrite an existing tag. If false (default), aKeyErroris raised.index (int | None)โ index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. IfNone(default), the tag is appended to the end of the order.
Raises:
KeyErrorโ if the tag key is already registered andforceis not true.Return type:
Nonetag(
value) โConvert a value to a tagged representation if necessary.
Parameters:
value (Any)โReturn type:
dict[str, Any]untag(
value) โConvert a tagged representation back to the original type.
Parameters:
value (dict[str, Any])โ
Return type:
Anyclassflask.json.tag.JSONTag(serializer) โBase class for defining type tags for
TaggedJSONSerializer.Parameters:
serializer (TaggedJSONSerializer)โ
check(
value) โCheck if the given value should be tagged by this tag.
Parameters:
value (Any)โ
Return type:
boolkey:
str | None = NoneโThe tag to mark the serialized object with. If
None, this tag is only used as an intermediate step during tagging.tag(
value) โConvert the value to a valid
JSONtype and add the tag structure around it.Parameters:
value (Any)โ
Return type:
Anyto_json(
value) โConvert the Python object to an object that is a valid
JSONtype. The tag will be added later.Parameters:
value (Any)โ
Return type:
Anyto_python(
value) โConvert the
JSONrepresentation back to the correct type. The tag will already be removed.Parameters:
value (Any)โ
Return type:
Any
Letโs see an example that adds support for OrderedDict. Dicts donโt have an order in JSON, so to handle this we will dump the items as a list of [key, value] pairs. Subclass JSONTag and give it the new key ' od' to identify the type. The session serializer processes dicts first, so insert the new tag at the front of the order since OrderedDict must be processed before dict.
from flask.json.tag import JSONTag
class TagOrderedDict(JSONTag):
__slots__ = ('serializer',)
key = ' od'
def check(self, value):
return isinstance(value, OrderedDict)
def to_json(self, value):
return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]
def to_python(self, value):
return OrderedDict(value)
app.session_interface.serializer.register(TagOrderedDict, index=0)from flask.json.tag import JSONTag
class TagOrderedDict(JSONTag):
__slots__ = ('serializer',)
key = ' od'
def check(self, value):
return isinstance(value, OrderedDict)
def to_json(self, value):
return [[k, self.serializer.tag(v)] for k, v in iteritems(value)]
def to_python(self, value):
return OrderedDict(value)
app.session_interface.serializer.register(TagOrderedDict, index=0)