Smarter Json Library

Overridden JSON utilities for the Smarter platform.

This module wraps the standard json library with the following enhancements:

  • Uses SmarterJSONEncoder as the default encoder.

  • Standardizes indentation to 2 characters.

  • Falls back to str() for non-serializable objects.

SmarterJSONEncoder adds serialization support for the following types:

The following symbols are re-exported unmodified from json:

exception smarter.lib.json.JSONDecodeError(msg, doc, pos)[source]

Bases: ValueError

Subclass of ValueError with the following additional properties:

msg: The unformatted error message doc: The JSON document being parsed pos: The start index of doc where parsing failed lineno: The line corresponding to pos colno: The column corresponding to pos

__init__(msg, doc, pos)[source]
class smarter.lib.json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)[source]

Bases: object

Simple JSON <https://json.org> decoder

Performs the following translations in decoding by default:

JSON

Python

object

dict

array

list

string

str

number (int)

int

number (real)

float

true

True

false

False

null

None

It also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec.

__init__(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)[source]

object_hook, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given dict. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting).

object_pairs_hook, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

parse_float, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.

If strict is false (true is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including '\t' (tab), '\n', '\r' and '\0'.

decode(s, _w=<built-in method match of re.Pattern object>)[source]

Return the Python representation of s (a str instance containing a JSON document).

raw_decode(s, idx=0)[source]

Decode a JSON document from s (a str beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended.

This can be used to decode a JSON document from a string that may have extraneous data at the end.

class smarter.lib.json.SmarterJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

A JSON encoder for the types that json.JSONEncoder can’t serialize.

It handles dates and times, decimals, UUIDs, Django’s lazy strings, sets, Pydantic urls, generic relations and taggit’s tags and managers. dumps() uses it by default, and Django model fields use it as their encoder.

default(o)[source]

Encode a value that json.JSONEncoder can’t.

Datetimes, dates and times become ISO 8601 strings, timedeltas ISO 8601 durations, decimals, UUIDs, lazy strings and urls strings, sets lists, and generic relations and taggit tags their names or lists.

Parameters:

o (Any) – The value.

Return type:

Any

Returns:

A JSON-serializable value.

Raises:
smarter.lib.json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)[source]

Serialize obj to a JSON string, with Smarter’s defaults.

The arguments are those of json.dumps(), with these defaults:

  • cls is SmarterJSONEncoder.

  • indent is 2.

  • A value that the encoder can’t serialize becomes str(value), unless default is given. The encoder still handles its own types first.

Parameters:

obj (object) – The value to serialize.

Return type:

str

Returns:

The JSON string.

smarter.lib.json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)[source]

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object.

object_hook is an optional function that will be called with the result of any object literal decode (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used.

smarter.lib.json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)[source]

Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object.

object_hook is an optional function that will be called with the result of any object literal decode (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders. If object_hook is also defined, the object_pairs_hook takes priority.

parse_float, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).

parse_int, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).

parse_constant, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered.

To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used.

smarter.lib.json.to_jsonable(obj, cls=None)[source]

Return obj as plain JSON data: dicts, lists, strings, numbers, booleans and None.

It is json.loads(dumps(obj)), without the indentation: an indented dump runs in pure Python, while a compact one runs in the standard library’s C encoder. Use it to snapshot data, e.g. before storing it in a JSONField.

Parameters:
Return type:

Any

Returns:

The JSON data.