flask.json package
Submodules
flask.json.provider module
- class flask.json.provider.DefaultJSONProvider(app: App)
Bases:
JSONProviderProvide JSON operations using Python’s built-in
jsonlibrary. Serializes the following additional data types:datetime.datetimeanddatetime.dateare serialized to RFC 822 strings. This is the same as the HTTP date 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.
- 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.
- static default(o: Any) Any
Apply this function to any object that
json.dumps()does not know how to serialize. It should return a valid JSON type or raise aTypeError.
- dumps(obj: Any, **kwargs: Any) str
Serialize data as JSON to a string.
Keyword arguments are passed to
json.dumps(). Sets some parameter defaults from thedefault,ensure_ascii, andsort_keysattributes.- Parameters:
obj – The data to serialize.
kwargs – Passed to
json.dumps().
- ensure_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.
- loads(s: str | bytes, **kwargs: Any) Any
Deserialize data as JSON from a string or bytes.
- Parameters:
s – Text or UTF-8 bytes.
kwargs – Passed to
json.loads().
- mimetype = 'application/json'
The mimetype set in
response().
- response(*args: t.Any, **kwargs: t.Any) Response
Serialize the given arguments as JSON, and return a
Responseobject with it. The response mimetype will be “application/json” and can be changed withmimetype.If
compactisFalseor 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 – A single value to serialize, or multiple values to treat as a list to serialize.
kwargs – Treat as a dict to serialize.
- 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.
- class flask.json.provider.JSONProvider(app: App)
Bases:
objectA 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()andloads(). All other methods have default implementations.To use a different provider, either subclass
Flaskand setjson_provider_classto a provider class, or setapp.jsonto an instance of the class.- Parameters:
app – An application instance. This will be stored as a
weakref.proxyon the_appattribute.
Added in version 2.2.
- dump(obj: Any, fp: IO[str], **kwargs: Any) None
Serialize data as JSON and write to a file.
- Parameters:
obj – The data to serialize.
fp – A file opened for writing text. Should use the UTF-8 encoding to be valid JSON.
kwargs – May be passed to the underlying JSON library.
- dumps(obj: Any, **kwargs: Any) str
Serialize data as JSON.
- Parameters:
obj – The data to serialize.
kwargs – May be passed to the underlying JSON library.
- load(fp: IO, **kwargs: Any) Any
Deserialize data as JSON read from a file.
- Parameters:
fp – A file opened for reading text or UTF-8 bytes.
kwargs – May be passed to the underlying JSON library.
- loads(s: str | bytes, **kwargs: Any) Any
Deserialize data as JSON.
- Parameters:
s – Text or UTF-8 bytes.
kwargs – May be passed to the underlying JSON library.
- response(*args: t.Any, **kwargs: t.Any) Response
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 – A single value to serialize, or multiple values to treat as a list to serialize.
kwargs – Treat as a dict to serialize.
flask.json.tag module
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: Any) str
Tag the value and dump it to a compact JSON string.
- loads(value: str) Any
Load data from a JSON string and deserialized any tagged objects.
- register(tag_class: type[JSONTag], force: bool = False, index: int | None = None) None
Register a new tag with this serializer.
- Parameters:
tag_class – tag class to register. Will be instantiated with this serializer instance.
force – overwrite an existing tag. If false (default), a
KeyErroris raised.index – index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. If
None(default), the tag is appended to the end of the order.
- Raises:
KeyError – if the tag key is already registered and
forceis not true.
- tag(value: Any) Any
Convert a value to a tagged representation if necessary.
- untag(value: dict[str, Any]) Any
Convert a tagged representation back to the original type.
- class flask.json.tag.JSONTag(serializer: TaggedJSONSerializer)
Base class for defining type tags for
TaggedJSONSerializer.- check(value: Any) bool
Check if the given value should be tagged by this tag.
- key: str = ''
The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.
- tag(value: Any) dict[str, Any]
Convert the value to a valid JSON type and add the tag structure around it.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- to_python(value: Any) Any
Convert the JSON representation back to the correct type. The tag will already be removed.
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)
- class flask.json.tag.JSONTag(serializer: TaggedJSONSerializer)
Bases:
objectBase class for defining type tags for
TaggedJSONSerializer.- check(value: Any) bool
Check if the given value should be tagged by this tag.
- key: str = ''
The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.
- serializer
- tag(value: Any) dict[str, Any]
Convert the value to a valid JSON type and add the tag structure around it.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- to_python(value: Any) Any
Convert the JSON representation back to the correct type. The tag will already be removed.
- class flask.json.tag.PassDict(serializer: TaggedJSONSerializer)
Bases:
JSONTag- check(value: Any) bool
Check if the given value should be tagged by this tag.
- tag(value: Any) Any
Convert the value to a valid JSON type and add the tag structure around it.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- class flask.json.tag.PassList(serializer: TaggedJSONSerializer)
Bases:
JSONTag- check(value: Any) bool
Check if the given value should be tagged by this tag.
- tag(value: Any) Any
Convert the value to a valid JSON type and add the tag structure around it.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- class flask.json.tag.TagBytes(serializer: TaggedJSONSerializer)
Bases:
JSONTag- check(value: Any) bool
Check if the given value should be tagged by this tag.
- key: str = ' b'
The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- to_python(value: Any) Any
Convert the JSON representation back to the correct type. The tag will already be removed.
- class flask.json.tag.TagDateTime(serializer: TaggedJSONSerializer)
Bases:
JSONTag- check(value: Any) bool
Check if the given value should be tagged by this tag.
- key: str = ' d'
The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- to_python(value: Any) Any
Convert the JSON representation back to the correct type. The tag will already be removed.
- class flask.json.tag.TagDict(serializer: TaggedJSONSerializer)
Bases:
JSONTagTag for 1-item dicts whose only key matches a registered tag.
Internally, the dict key is suffixed with __, and the suffix is removed when deserializing.
- check(value: Any) bool
Check if the given value should be tagged by this tag.
- key: str = ' di'
The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- to_python(value: Any) Any
Convert the JSON representation back to the correct type. The tag will already be removed.
- class flask.json.tag.TagMarkup(serializer: TaggedJSONSerializer)
Bases:
JSONTagSerialize anything matching the
MarkupAPI by having a__html__method to the result of that method. Always deserializes to an instance ofMarkup.- check(value: Any) bool
Check if the given value should be tagged by this tag.
- key: str = ' m'
The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- to_python(value: Any) Any
Convert the JSON representation back to the correct type. The tag will already be removed.
- class flask.json.tag.TagTuple(serializer: TaggedJSONSerializer)
Bases:
JSONTag- check(value: Any) bool
Check if the given value should be tagged by this tag.
- key: str = ' t'
The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- to_python(value: Any) Any
Convert the JSON representation back to the correct type. The tag will already be removed.
- class flask.json.tag.TagUUID(serializer: TaggedJSONSerializer)
Bases:
JSONTag- check(value: Any) bool
Check if the given value should be tagged by this tag.
- key: str = ' u'
The tag to mark the serialized object with. If empty, this tag is only used as an intermediate step during tagging.
- to_json(value: Any) Any
Convert the Python object to an object that is a valid JSON type. The tag will be added later.
- to_python(value: Any) Any
Convert the JSON representation back to the correct type. The tag will already be removed.
- class flask.json.tag.TaggedJSONSerializer
Bases:
objectSerializer 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: Any) str
Tag the value and dump it to a compact JSON string.
- loads(value: str) Any
Load data from a JSON string and deserialized any tagged objects.
- register(tag_class: type[JSONTag], force: bool = False, index: int | None = None) None
Register a new tag with this serializer.
- Parameters:
tag_class – tag class to register. Will be instantiated with this serializer instance.
force – overwrite an existing tag. If false (default), a
KeyErroris raised.index – index to insert the new tag in the tag order. Useful when the new tag is a special case of an existing tag. If
None(default), the tag is appended to the end of the order.
- Raises:
KeyError – if the tag key is already registered and
forceis not true.
- tag(value: Any) Any
Convert a value to a tagged representation if necessary.
- untag(value: dict[str, Any]) Any
Convert a tagged representation back to the original type.
Module contents
- flask.json.dump(obj: Any, fp: IO[str], **kwargs: Any) None
Serialize data as JSON and write to a file.
If
current_appis available, it will use itsapp.json.dump()method, otherwise it will usejson.dump().- Parameters:
obj – The data to serialize.
fp – A file opened for writing text. Should use the UTF-8 encoding to be valid JSON.
kwargs – Arguments passed to the
dumpimplementation.
Changed in version 2.3: The
appparameter was removed.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
encodingargument, will be removed in Flask 2.1.
- flask.json.dumps(obj: Any, **kwargs: Any) str
Serialize data as JSON.
If
current_appis available, it will use itsapp.json.dumps()method, otherwise it will usejson.dumps().- Parameters:
obj – The data to serialize.
kwargs – Arguments passed to the
dumpsimplementation.
Changed in version 2.3: The
appparameter was removed.Changed in version 2.2: Calls
current_app.json.dumps, allowing an app to override the behavior.Changed in version 2.0.2:
decimal.Decimalis supported by converting to a string.Changed in version 2.0:
encodingwill be removed in Flask 2.1.Changed in version 1.0.3:
appcan be passed directly, rather than requiring an app context for configuration.
- flask.json.jsonify(*args: t.Any, **kwargs: t.Any) Response
Serialize the given arguments as JSON, and return a
Responseobject with theapplication/jsonmimetype. 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,
Noneis serialized.- Parameters:
args – A single value to serialize, or multiple values to treat as a list to serialize.
kwargs – Treat as a dict to serialize.
Changed in version 2.2: Calls
current_app.json.response, allowing an app to override the behavior.Changed in version 2.0.2:
decimal.Decimalis 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 security-json.
Added in version 0.2.
- flask.json.load(fp: IO, **kwargs: Any) Any
Deserialize data as JSON read from a file.
If
current_appis available, it will use itsapp.json.load()method, otherwise it will usejson.load().- Parameters:
fp – A file opened for reading text or UTF-8 bytes.
kwargs – Arguments passed to the
loadimplementation.
Changed in version 2.3: The
appparameter was removed.Changed in version 2.2: Calls
current_app.json.load, allowing an app to override the behavior.Changed in version 2.2: The
appparameter will be removed in Flask 2.3.Changed in version 2.0:
encodingwill be removed in Flask 2.1. The file must be text mode, or binary mode with UTF-8 bytes.
- flask.json.loads(s: str | bytes, **kwargs: Any) Any
Deserialize data as JSON.
If
current_appis available, it will use itsapp.json.loads()method, otherwise it will usejson.loads().- Parameters:
s – Text or UTF-8 bytes.
kwargs – Arguments passed to the
loadsimplementation.
Changed in version 2.3: The
appparameter was removed.Changed in version 2.2: Calls
current_app.json.loads, allowing an app to override the behavior.Changed in version 2.0:
encodingwill be removed in Flask 2.1. The data must be a string or UTF-8 bytes.Changed in version 1.0.3:
appcan be passed directly, rather than requiring an app context for configuration.