11. JSON Support

Flask uses simplejson for the JSON implementation. Since simplejson is provided by both the standard library as well as extension, Flask will try simplejson first and then fall back to the stdlib json module. On top of that it will delegate access to the current application’s JSON encoders and decoders for easier customization.

So for starters instead of doing:

try:
    import simplejson as json
except ImportError:
    import json

You can instead just do this:

from flask import json

For usage examples, read the json documentation in the standard library. The following extensions are by default applied to the stdlib’s JSON module:

  1. datetime objects are serialized as RFC 822 strings.
  2. Any object with an __html__ method (like Markup) will have that method called and then the return value is serialized as string.

The htmlsafe_dumps() function of this json module is also available as filter called |tojson in Jinja2. Note that inside script tags no escaping must take place, so make sure to disable escaping with |safe if you intend to use it inside script tags unless you are using Flask 0.10 which implies that:

<script type=text/javascript>
    doSomethingWith({{ user.username|tojson|safe }});
</script>

Auto-Sort JSON Keys

The configuration variable JSON_SORT_KEYS (1   Configuration Handling) can be set to false to stop Flask from auto-sorting keys. By default sorting is enabled and outside of the app context sorting is turned on.

Notice that disabling key sorting can cause issues when using content based HTTP caches and Python’s hash randomization feature.

flask.json.jsonify(*args, **kwargs)[source]

This function wraps dumps() to add a few enhancements that make life easier. It turns the JSON output into a Response object with the application/json mimetype. For convenience, it also converts multiple arguments into an array or multiple keyword arguments into a dict. This means that both jsonify(1,2,3) and jsonify([1,2,3]) serialize to [1,2,3].

For clarity, the JSON serialization behavior has the following differences from dumps():

  1. Single argument: Passed straight through to dumps().
  2. Multiple arguments: Converted to an array before being passed to dumps().
  3. Multiple keyword arguments: Converted to a dict before being passed to dumps().
  4. Both args and kwargs: Behavior undefined and will throw an exception.

Example usage:

from flask import jsonify

@app.route('/_get_current_user')
def get_current_user():
    return jsonify(username=g.user.username,
                   email=g.user.email,
                   id=g.user.id)

This will send a JSON response like this to the browser:

{
    "username": "admin",
    "email": "admin@localhost",
    "id": 42
}

Changed in version 0.11: Added support for serializing top-level arrays. This introduces a security risk in ancient browsers. See JSON Security for details.

This function’s response will be pretty printed if it was not requested with X-Requested-With: XMLHttpRequest to simplify debugging unless the JSONIFY_PRETTYPRINT_REGULAR config parameter is set to false. Compressed (not pretty) formatting currently means no indents and no spaces after separators.

New in version 0.2.

flask.json.dumps(obj, **kwargs)[source]

Serialize obj to a JSON formatted str by using the application’s configured encoder (json_encoder) if there is an application on the stack.

This function can return unicode strings or ascii-only bytestrings by default which coerce into unicode strings automatically. That behavior by default is controlled by the JSON_AS_ASCII configuration variable and can be overridden by the simplejson ensure_ascii parameter.

flask.json.dump(obj, fp, **kwargs)[source]

Like dumps() but writes into a file object.

flask.json.loads(s, **kwargs)[source]

Unserialize a JSON object from a string s by using the application’s configured decoder (json_decoder) if there is an application on the stack.

flask.json.load(fp, **kwargs)[source]

Like loads() but reads from a file object.

class flask.json.JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, for_json=False, ignore_nan=False, int_as_string_bitcount=None, iterable_as_array=False)[source]

The default Flask JSON encoder. This one extends the default simplejson encoder by also supporting datetime objects, UUID as well as Markup objects which are serialized as RFC 822 datetime strings (same as the HTTP date format). In order to support more data types override the default() method.

default(o)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    return JSONEncoder.default(self, o)
class flask.json.JSONDecoder(encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)[source]

The default JSON decoder. This one does not change the behavior from the default simplejson decoder. Consult the json documentation for more information. This decoder is not only used for the load functions of this module but also Request.