Skip to the content.

JSON Tools

Auto-generated documentation for dynamo_query.json_tools module.

Safe JSON SerDe.

SafeJSONEncoder

[find in source code]

class SafeJSONEncoder(json.JSONEncoder):

Safe encoder for json.dumps. Handles decimal.Decimal values properly and uses repr for any non-serializeable object.

data = {
    'string': 'test',
    'decimal': decimal.Decimal('3.14'),
    'datetime': datetime.datetime(2020, 1, 15, 14, 34, 56),
    'date': datetime.date(2020, 1, 15),
    'exception': ValueError('test'),
}
json.dumps(data, cls=SafeJSONEncoder)

SafeJSONEncoder().default

[find in source code]

def default(o: Any) -> Any:

Override handling of non-JSON-serializeable objects. Supports decimal.Decimal and set.

Arguments

Returns

int or float for decimal values, otherwise a string with object representation.

dumps

[find in source code]

def dumps(
    data: Any,
    sort_keys: bool = True,
    cls: Type[json.JSONEncoder] = SafeJSONEncoder,
    **kwargs: Any,
) -> str:

Alias for json.dumps. Uses SafeJSONEncoder to serialize Decimals and non-serializeable objects. Sorts dict keys by default.

Arguments

Returns

A string with serialized JSON.

See also

loads

[find in source code]

def loads(data: str, **kwargs: Any) -> Any:

Alias for json.loads.

Arguments

Returns

An object created from JSON data.