Smarter Json Library
Overridden JSON utilities for the Smarter platform.
This module wraps the standard json library with the following enhancements:
Uses
SmarterJSONEncoderas the default encoder.Standardizes indentation to 2 characters.
Falls back to
str()for non-serializable objects.
SmarterJSONEncoder adds serialization support for the following types:
datetime.datetime,datetime.date,datetime.time,datetime.timedeltataggit.managers.TaggableManager
The following symbols are re-exported unmodified from json:
- exception smarter.lib.json.JSONDecodeError(msg, doc, pos)[source]
Bases:
ValueErrorSubclass 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
- 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:
objectSimple 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-Infinityas their correspondingfloatvalues, 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 givendict. 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 ofobject_pairs_hookwill be used instead of thedict. This feature can be used to implement custom decoders. Ifobject_hookis also defined, theobject_pairs_hooktakes 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
strictis 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'.
- 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:
JSONEncoderA JSON encoder for the types that
json.JSONEncodercan’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 theirencoder.- default(o)[source]
Encode a value that
json.JSONEncodercan’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:
- Returns:
A JSON-serializable value.
- Raises:
ValueError – For a timezone-aware time.
TypeError – For any other type, from
json.JSONEncoder.default().
- 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
objto a JSON string, with Smarter’s defaults.The arguments are those of
json.dumps(), with these defaults:clsisSmarterJSONEncoder.indentis 2.A value that the encoder can’t serialize becomes
str(value), unlessdefaultis given. The encoder still handles its own types first.
- 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_hookis an optional function that will be called with the result of any object literal decode (adict). The return value ofobject_hookwill be used instead of thedict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).object_pairs_hookis an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value ofobject_pairs_hookwill be used instead of thedict. This feature can be used to implement custom decoders. Ifobject_hookis also defined, theobject_pairs_hooktakes priority.To use a custom
JSONDecodersubclass, specify it with theclskwarg; otherwiseJSONDecoderis 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(astr,bytesorbytearrayinstance containing a JSON document) to a Python object.object_hookis an optional function that will be called with the result of any object literal decode (adict). The return value ofobject_hookwill be used instead of thedict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).object_pairs_hookis an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value ofobject_pairs_hookwill be used instead of thedict. This feature can be used to implement custom decoders. Ifobject_hookis also defined, theobject_pairs_hooktakes 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
JSONDecodersubclass, specify it with theclskwarg; otherwiseJSONDecoderis used.
- smarter.lib.json.to_jsonable(obj, cls=None)[source]
Return
objas 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 aJSONField.- Parameters:
obj (
Any) – The value to convert.cls (
type[JSONEncoder] |None) – The encoder;SmarterJSONEncoderby default. Values it can’t encode becomestr(value).
- Return type:
- Returns:
The JSON data.