flask.json package

Submodules

flask.json.provider module

class flask.json.provider.DefaultJSONProvider(app: App)

Bases: JSONProvider

Provide JSON operations using Python’s built-in json library. Serializes the following additional data types:

  • datetime.datetime and datetime.date are serialized to RFC 822 strings. This is the same as the HTTP date format.

  • uuid.UUID is serialized to a string.

  • dataclasses.dataclass is passed to dataclasses.asdict().

  • Markup (or any object with a __html__ method) will call the __html__ method to get a string.

compact: bool | None = None

If True, or None out of debug mode, the response() output will not add indentation, newlines, or spaces. If False, or None in 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 a TypeError.

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 the default, ensure_ascii, and sort_keys attributes.

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 Response object with it. The response mimetype will be “application/json” and can be changed with mimetype.

If compact is False or 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, None is 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: object

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 – An application instance. This will be stored as a weakref.proxy on the _app attribute.

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 Response object with the application/json mimetype.

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, None is 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:

  • dict

  • tuple

  • bytes

  • Markup

  • UUID

  • datetime

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 KeyError is 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 force is 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: object

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.

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: JSONTag

Tag 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: JSONTag

Serialize anything matching the Markup API by having a __html__ method to the result of that method. Always deserializes to an instance of Markup.

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: object

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:

  • dict

  • tuple

  • bytes

  • Markup

  • UUID

  • datetime

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.

order: list[JSONTag]
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 KeyError is 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 force is not true.

tag(value: Any) Any

Convert a value to a tagged representation if necessary.

tags: dict[str, JSONTag]
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_app is available, it will use its app.json.dump() method, otherwise it will use json.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 dump implementation.

Changed in version 2.3: The app parameter 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 encoding argument, will be removed in Flask 2.1.

flask.json.dumps(obj: Any, **kwargs: Any) str

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 – The data to serialize.

  • kwargs – Arguments passed to the dumps implementation.

Changed in version 2.3: The app parameter 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.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.jsonify(*args: t.Any, **kwargs: t.Any) Response

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 – 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.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 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_app is available, it will use its app.json.load() method, otherwise it will use json.load().

Parameters:
  • fp – A file opened for reading text or UTF-8 bytes.

  • kwargs – Arguments passed to the load implementation.

Changed in version 2.3: The app parameter 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 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.

flask.json.loads(s: str | bytes, **kwargs: Any) Any

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 – Text or UTF-8 bytes.

  • kwargs – Arguments passed to the loads implementation.

Changed in version 2.3: The app parameter was removed.

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.