bokeh.core.json_encoder#

Provide a functions and classes to implement a custom JSON encoder for serializing objects for BokehJS.

The primary interface is provided by the serialize_json function, which uses the custom BokehJSONEncoder to produce JSON output.

In general, functions in this module convert values in the following way:

  • Datetime values (Python, Pandas, NumPy) are converted to floating point milliseconds since epoch.

  • TimeDelta values are converted to absolute floating point milliseconds.

  • RelativeDelta values are converted to dictionaries.

  • Decimal values are converted to floating point.

  • Sequences (Pandas Series, NumPy arrays, python sequences) that are passed though this interface are converted to lists. Note, however, that arrays in data sources inside Bokeh Documents are converted elsewhere, and by default use a binary encoded format.

  • Bokeh Model instances are usually serialized elsewhere in the context of an entire Bokeh Document. Models passed trough this interface are converted to references.

  • HasProps (that are not Bokeh models) are converted to key/value dicts or all their properties and values.

  • Color instances are converted to CSS color values.

serialize_json(obj: Any, pretty: bool | None = None, indent: int | None = None, **kwargs: Any) str[source]#

Return a serialized JSON representation of objects, suitable to send to BokehJS.

This function is typically used to serialize single python objects in the manner expected by BokehJS. In particular, many datetime values are automatically normalized to an expected format. Some Bokeh objects can also be passed, but note that Bokeh models are typically properly serialized in the context of an entire Bokeh document.

The resulting JSON always has sorted keys. By default. the output is as compact as possible unless pretty output or indentation is requested.

Parameters
  • obj (obj) – the object to serialize to JSON format

  • pretty (bool, optional) –

    Whether to generate prettified output. If True, spaces are added after added after separators, and indentation and newlines are applied. (default: False)

    Pretty output can also be enabled with the environment variable BOKEH_PRETTY, which overrides this argument, if set.

  • indent (int or None, optional) – Amount of indentation to use in generated JSON output. If None then no indentation is used, unless pretty output is enabled, in which case two spaces are used. (default: None)

Any additional keyword arguments are passed to json.dumps, except for some that are computed internally, and cannot be overridden:

  • allow_nan

  • indent

  • separators

  • sort_keys

Examples

>>> data = dict(b=np.datetime64('2017-01-01'), a = np.arange(3))

>>>print(serialize_json(data))
{"a":[0,1,2],"b":1483228800000.0}

>>> print(serialize_json(data, pretty=True))
{
  "a": [
    0,
    1,
    2
  ],
  "b": 1483228800000.0
}
class BokehJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]#

Bases: JSONEncoder

A custom json.JSONEncoder subclass for encoding objects in accordance with the BokehJS protocol.

Public Data Attributes:

Inherited from JSONEncoder

item_separator

key_separator

Public Methods:

transform_python_types(obj)

Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values.

default(obj)

The required default method for JSONEncoder subclasses.

Inherited from JSONEncoder

__init__(*[, skipkeys, ensure_ascii, ...])

Constructor for JSONEncoder, with sensible defaults.

default(obj)

The required default method for JSONEncoder subclasses.

encode(o)

Return a JSON string representation of a Python data structure.

iterencode(o[, _one_shot])

Encode the given object and yield each string representation as available.


__init__(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)#

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

default(obj: Any) Any[source]#

The required default method for JSONEncoder subclasses.

Parameters

obj (obj) – The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder.

encode(o)#

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
iterencode(o, _one_shot=False)#

Encode the given object and yield each string representation as available.

For example:

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
transform_python_types(obj: Any) Any[source]#

Handle special scalars such as (Python, NumPy, or Pandas) datetimes, or Decimal values.

Parameters

obj (obj) – The object to encode. Anything not specifically handled in this method is passed on to the default system JSON encoder.