pylav.compat package#

Submodules#

pylav.compat.json module#

exception pylav.compat.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

class pylav.compat.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.

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 pylav.compat.json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]#

Bases: object

Extensible JSON <https://json.org> encoder for Python data structures.

Supports the following objects and types by default:

Python

JSON

dict

object

list, tuple

array

str

string

int, float

number

True

true

False

false

None

null

To extend this to recognize other objects, subclass and implement a .default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).

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)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
encode(o)[source]#

Return a JSON string representation of a Python data structure.

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

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

For example:

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)
key_separator = ': '#
pylav.compat.json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, ujson_encode_html_chars=False, ujson_escape_forward_slashes=True, **kwargs)[source]#

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object).

pylav.compat.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, orjson_default=None, orjson_option=None, ujson_encode_html_chars=False, ujson_escape_forward_slashes=True, **kwargs)[source]#

Serialize obj to a JSON formatted str.

Parameters:
  • obj (Any) – The object to serialize.

  • skipkeys (bool, optional) – If True (default: False), keys that are not basic types (str, int, float, bool, None) will be skipped instead of raising a TypeError.

  • ensure_ascii (bool, optional) – If True (default: True), the output is guaranteed to have all incoming non-ASCII characters escaped. If False, these characters will be output as-is.

  • check_circular (bool, optional) – If check_circular is False (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an RecursionError (or worse).

  • allow_nan (bool, optional) – If False (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification. If True, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used.

  • cls (type, optional) – If specified, must be a subclass of json.JSONEncoder. An instance is used to encode the object.

  • indent (int or str, optional) – If specified, then JSON array elements and object members will be pretty-printed with a newline followed by that many spaces. An indent level of 0, negative, or None will only insert newlines. None is the most compact representation. Using a negative indent indents that many spaces after the newline character. If it is a string (such as '      '), that string is used to indent each level. Default: None.

  • separators (tuple, optional) – If specified, then it 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.

  • default (Callable, optional) – If specified, then it should be 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. If not specified, TypeError is raised.

  • sort_keys (bool, optional) – If True (default: False), then the output of dictionaries will be sorted by key.

  • orjson_default (Callable, optional) – If specified, then it should be 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. If not specified, TypeError is raised.

  • orjson_option (int, optional) – If specified, then it should be an integer that is passed to orjson.dumps as the option parameter. If not specified, None is used.

  • ujson_encode_html_chars (bool, optional) – If True (default: False), then the output will have the characters <, >, & encoded as <, >, &.

  • ujson_escape_forward_slashes – If True (default: True), then the output will have the forward slash character / encoded as \/.

  • kwargs (Any, optional) – Additional keyword arguments are passed to json.dumps.

Returns:

The JSON string representation of obj.

Return type:

str

pylav.compat.json.get_origin()[source]#

Return a dict of json modules being used.

pylav.compat.json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, precise_float=None, **kwargs)[source]#

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

pylav.compat.json.loads(obj, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, ujson_precise_float=None, **kwargs)[source]#

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

Parameters:
  • obj (AnyStr | bytes | bytearray | memoryview | str) – The JSON string to deserialize.

  • cls (type, optional) – If specified, must be a subclass of json.JSONDecoder. An instance is used to decode the object.

  • object_hook (Callable, optional) – If specified, then it should be a function that will be called with the result of any object literal decoded (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).

  • parse_float (Callable, optional) – If specified, then it should be a function to 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 (Callable, optional) – If specified, then it should be a function to 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 (Callable, optional) – If specified, then it should be a function to 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.

  • object_pairs_hook (Callable, optional) – If specified, then it should be a 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.

  • ujson_precise_float (bool, optional) – If True (default: False), then

  • kwargs (Any, optional) – Additional keyword arguments are passed to json.loads.

Returns:

The deserialized object.

Return type:

Any

Raises:

json.JSONDecodeError – If the input is not valid JSON.

:raises orjson.JSONDecodeError(json.JSONDecodeError`, :class:`ValueError): If the input is not valid JSON and orjson is used. :raises ValueError: If the string is not correctly formed and ujson is used.

Module contents#