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 correspondingfloat
values, which is outside the JSON spec.
- 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 foro
if possible, otherwise it should call the superclass implementation (to raiseTypeError
).- 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 aTypeError
).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 tofp
(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 formattedstr
.- Parameters:
obj (
Any
) – The object to serialize.skipkeys (
bool
, optional) – IfTrue
(default:False
), keys that are not basic types (str
,int
,float
,bool
,None
) will be skipped instead of raising aTypeError
.ensure_ascii (
bool
, optional) – IfTrue
(default:True
), the output is guaranteed to have all incoming non-ASCII characters escaped. IfFalse
, these characters will be output as-is.check_circular (
bool
, optional) – If check_circular isFalse
(default:True
), then the circular reference check for container types will be skipped and a circular reference will result in anRecursionError
(or worse).allow_nan (
bool
, optional) – IfFalse
(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. IfTrue
, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used.cls (
type
, optional) – If specified, must be a subclass ofjson.JSONEncoder
. An instance is used to encode the object.indent (
int
orstr
, 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, orNone
will only insert newlines.None
is the most compact representation. Using a negative indent indents that many spaces after thenewline
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 isNone
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 aTypeError
. If not specified,TypeError
is raised.sort_keys (
bool
, optional) – IfTrue
(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 aTypeError
. If not specified,TypeError
is raised.orjson_option (
int
, optional) – If specified, then it should be an integer that is passed toorjson.dumps
as theoption
parameter. If not specified,None
is used.ujson_encode_html_chars (
bool
, optional) – IfTrue
(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 tojson.dumps
.
- Returns:
The JSON string representation of
obj
.- Return type:
- 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
(astr
,bytes
orbytearray
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 ofjson.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 (adict
). The return value ofobject_hook
will be used instead of thedict
. 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 tofloat(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 toint(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 ofobject_pairs_hook
will be used instead of thedict
. This feature can be used to implement custom decoders. Ifobject_hook
is also defined, theobject_pairs_hook
takes priority.ujson_precise_float (
bool
, optional) – IfTrue
(default:False
), thenkwargs (
Any
, optional) – Additional keyword arguments are passed tojson.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.