cengal.parallel_execution.coroutines.coro_tools.low_latency.json.versions.v_0.json
Module Docstring Docstrings: http://www.python.org/dev/peps/pep-0257/
1#!/usr/bin/env python 2# coding=utf-8 3 4# Copyright © 2012-2024 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space> 5# 6# Licensed under the Apache License, Version 2.0 (the "License"); 7# you may not use this file except in compliance with the License. 8# You may obtain a copy of the License at 9# 10# http://www.apache.org/licenses/LICENSE-2.0 11# 12# Unless required by applicable law or agreed to in writing, software 13# distributed under the License is distributed on an "AS IS" BASIS, 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15# See the License for the specific language governing permissions and 16# limitations under the License. 17 18""" 19Module Docstring 20Docstrings: http://www.python.org/dev/peps/pep-0257/ 21""" 22 23__author__ = "ButenkoMS <gtalk@butenkoms.space>" 24__copyright__ = "Copyright © 2012-2024 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space>" 25__credits__ = ["ButenkoMS <gtalk@butenkoms.space>", ] 26__license__ = "Apache License, Version 2.0" 27__version__ = "4.4.1" 28__maintainer__ = "ButenkoMS <gtalk@butenkoms.space>" 29__email__ = "gtalk@butenkoms.space" 30# __status__ = "Prototype" 31__status__ = "Development" 32# __status__ = "Production" 33 34 35__all__ = ['LowLatencyJSONDecoder', 'LowLatencyJSONEncoder', 'LowLatencyObjectPairsHook', 'original_json_dump', 'original_json_dumps', 'original_json_load', 'original_json_loads'] 36 37 38import json 39 40original_json_dump = json.dump 41original_json_dumps = json.dumps 42original_json_load = json.load 43original_json_loads = json.loads 44 45 46def dump(*args, **kwargs): 47 # You may use 48 # ly = None, priority: CoroPriority = CoroPriority.normal 49 # as an additional parameters in order to configure LowLatencyJSONEncoder 50 51 kwargs['cls'] = LowLatencyJSONEncoder 52 return original_json_dump(*args, **kwargs) 53 54 55def dumps(*args, **kwargs): 56 # You may use 57 # ly = None, priority: CoroPriority = CoroPriority.normal 58 # as an additional parameters in order to configure LowLatencyJSONEncoder 59 60 kwargs['cls'] = LowLatencyJSONEncoder 61 return original_json_dumps(*args, **kwargs) 62 63 64def load(*args, **kwargs): 65 # You may use 66 # ly = None, priority: CoroPriority = CoroPriority.normal 67 # as an additional parameters in order to configure LowLatencyJSONEncoder 68 69 kwargs['cls'] = LowLatencyJSONDecoder 70 kwargs['object_pairs_hook'] = LowLatencyObjectPairsHook(**kwargs) 71 return original_json_load(*args, **kwargs) 72 73 74def loads(*args, **kwargs): 75 # You may use 76 # ly = None, priority: CoroPriority = CoroPriority.normal 77 # as an additional parameters in order to configure LowLatencyJSONEncoder 78 79 kwargs['cls'] = LowLatencyJSONDecoder 80 kwargs['object_pairs_hook'] = LowLatencyObjectPairsHook(**kwargs) 81 return original_json_loads(*args, **kwargs) 82 83 84# json.dump = dump 85# json.dumps = dumps 86# json.load = load 87# json.loads = loads 88 89 90def low_latency_json_mock_all(): 91 json.dump = dump 92 json.dumps = dumps 93 json.load = load 94 json.loads = loads 95 96 97def low_latency_json_demock_all(): 98 json.dump = original_json_dump 99 json.dumps = original_json_dumps 100 json.load = original_json_load 101 json.loads = original_json_loads 102 103 104from cengal.parallel_execution.coroutines.coro_standard_services.loop_yield import * 105from typing import Any, Optional, Callable, Tuple, Dict, List 106 107 108class LowLatencyJSONDecoder(json.JSONDecoder): 109 def __init__(self, *, object_hook: Optional[Callable[[Dict[str, Any]], Any]] = None, parse_float: Optional[Callable[[str], Any]] = None, parse_int: Optional[Callable[[str], Any]] = None, parse_constant: Optional[Callable[[str], Any]] = None, strict: bool = True, object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = None, ly = None, priority: CoroPriority = CoroPriority.normal) -> None: 110 super().__init__(object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, strict=strict, object_pairs_hook=object_pairs_hook) 111 self.ly = ly or gly(priority) 112 self.ly() 113 114 115class LowLatencyJSONEncoder(json.JSONEncoder): 116 def __init__(self, *, skipkeys: bool = False, ensure_ascii: bool = True, check_circular: bool = True, allow_nan: bool = True, sort_keys: bool = False, indent: Optional[int] = None, separators: Optional[Tuple[str, str]] = None, default: Optional[Callable[..., Any]] = None, ly = None, priority: CoroPriority = CoroPriority.normal) -> None: 117 super().__init__(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, sort_keys=sort_keys, indent=indent, separators=separators, default=default) 118 self._original_iterencode = self.iterencode 119 self.iterencode = self._low_latency_iterencode 120 self.ly = ly or gly(priority) 121 self.ly() 122 123 def _low_latency_iterencode(self, *args, **kwargs): 124 self.ly() 125 return self._original_iterencode(*args, **kwargs) 126 127 128class LowLatencyObjectPairsHook: 129 def __init__(self, ly = None, priority: CoroPriority = CoroPriority.normal, **kwargs) -> None: 130 self.ly = ly or gly(priority) 131 132 def __call__(self, pairs) -> Any: 133 self.ly() 134 return dict(pairs)
109class LowLatencyJSONDecoder(json.JSONDecoder): 110 def __init__(self, *, object_hook: Optional[Callable[[Dict[str, Any]], Any]] = None, parse_float: Optional[Callable[[str], Any]] = None, parse_int: Optional[Callable[[str], Any]] = None, parse_constant: Optional[Callable[[str], Any]] = None, strict: bool = True, object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = None, ly = None, priority: CoroPriority = CoroPriority.normal) -> None: 111 super().__init__(object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, strict=strict, object_pairs_hook=object_pairs_hook) 112 self.ly = ly or gly(priority) 113 self.ly()
Simple JSON http://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.
110 def __init__(self, *, object_hook: Optional[Callable[[Dict[str, Any]], Any]] = None, parse_float: Optional[Callable[[str], Any]] = None, parse_int: Optional[Callable[[str], Any]] = None, parse_constant: Optional[Callable[[str], Any]] = None, strict: bool = True, object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = None, ly = None, priority: CoroPriority = CoroPriority.normal) -> None: 111 super().__init__(object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, strict=strict, object_pairs_hook=object_pairs_hook) 112 self.ly = ly or gly(priority) 113 self.ly()
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'
.
Inherited Members
- json.decoder.JSONDecoder
- object_hook
- parse_float
- parse_int
- parse_constant
- strict
- object_pairs_hook
- parse_object
- parse_array
- parse_string
- memo
- scan_once
- decode
- raw_decode
116class LowLatencyJSONEncoder(json.JSONEncoder): 117 def __init__(self, *, skipkeys: bool = False, ensure_ascii: bool = True, check_circular: bool = True, allow_nan: bool = True, sort_keys: bool = False, indent: Optional[int] = None, separators: Optional[Tuple[str, str]] = None, default: Optional[Callable[..., Any]] = None, ly = None, priority: CoroPriority = CoroPriority.normal) -> None: 118 super().__init__(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, sort_keys=sort_keys, indent=indent, separators=separators, default=default) 119 self._original_iterencode = self.iterencode 120 self.iterencode = self._low_latency_iterencode 121 self.ly = ly or gly(priority) 122 self.ly() 123 124 def _low_latency_iterencode(self, *args, **kwargs): 125 self.ly() 126 return self._original_iterencode(*args, **kwargs)
Extensible JSON http://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
).
117 def __init__(self, *, skipkeys: bool = False, ensure_ascii: bool = True, check_circular: bool = True, allow_nan: bool = True, sort_keys: bool = False, indent: Optional[int] = None, separators: Optional[Tuple[str, str]] = None, default: Optional[Callable[..., Any]] = None, ly = None, priority: CoroPriority = CoroPriority.normal) -> None: 118 super().__init__(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, sort_keys=sort_keys, indent=indent, separators=separators, default=default) 119 self._original_iterencode = self.iterencode 120 self.iterencode = self._low_latency_iterencode 121 self.ly = ly or gly(priority) 122 self.ly()
Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.
If specified, separators 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.
If specified, default is 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
.
205 def iterencode(self, o, _one_shot=False): 206 """Encode the given object and yield each string 207 representation as available. 208 209 For example:: 210 211 for chunk in JSONEncoder().iterencode(bigobject): 212 mysocket.write(chunk) 213 214 """ 215 if self.check_circular: 216 markers = {} 217 else: 218 markers = None 219 if self.ensure_ascii: 220 _encoder = encode_basestring_ascii 221 else: 222 _encoder = encode_basestring 223 224 def floatstr(o, allow_nan=self.allow_nan, 225 _repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY): 226 # Check for specials. Note that this type of test is processor 227 # and/or platform-specific, so do tests which don't depend on the 228 # internals. 229 230 if o != o: 231 text = 'NaN' 232 elif o == _inf: 233 text = 'Infinity' 234 elif o == _neginf: 235 text = '-Infinity' 236 else: 237 return _repr(o) 238 239 if not allow_nan: 240 raise ValueError( 241 "Out of range float values are not JSON compliant: " + 242 repr(o)) 243 244 return text 245 246 247 if (_one_shot and c_make_encoder is not None 248 and self.indent is None): 249 _iterencode = c_make_encoder( 250 markers, self.default, _encoder, self.indent, 251 self.key_separator, self.item_separator, self.sort_keys, 252 self.skipkeys, self.allow_nan) 253 else: 254 _iterencode = _make_iterencode( 255 markers, self.default, _encoder, self.indent, floatstr, 256 self.key_separator, self.item_separator, self.sort_keys, 257 self.skipkeys, _one_shot) 258 return _iterencode(o, 0)
Encode the given object and yield each string representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
Inherited Members
- json.encoder.JSONEncoder
- item_separator
- key_separator
- skipkeys
- ensure_ascii
- check_circular
- allow_nan
- sort_keys
- indent
- default
- encode
129class LowLatencyObjectPairsHook: 130 def __init__(self, ly = None, priority: CoroPriority = CoroPriority.normal, **kwargs) -> None: 131 self.ly = ly or gly(priority) 132 133 def __call__(self, pairs) -> Any: 134 self.ly() 135 return dict(pairs)
121def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, 122 allow_nan=True, cls=None, indent=None, separators=None, 123 default=None, sort_keys=False, **kw): 124 """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a 125 ``.write()``-supporting file-like object). 126 127 If ``skipkeys`` is true then ``dict`` keys that are not basic types 128 (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped 129 instead of raising a ``TypeError``. 130 131 If ``ensure_ascii`` is false, then the strings written to ``fp`` can 132 contain non-ASCII characters if they appear in strings contained in 133 ``obj``. Otherwise, all such characters are escaped in JSON strings. 134 135 If ``check_circular`` is false, then the circular reference check 136 for container types will be skipped and a circular reference will 137 result in an ``OverflowError`` (or worse). 138 139 If ``allow_nan`` is false, then it will be a ``ValueError`` to 140 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) 141 in strict compliance of the JSON specification, instead of using the 142 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). 143 144 If ``indent`` is a non-negative integer, then JSON array elements and 145 object members will be pretty-printed with that indent level. An indent 146 level of 0 will only insert newlines. ``None`` is the most compact 147 representation. 148 149 If specified, ``separators`` should be an ``(item_separator, key_separator)`` 150 tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and 151 ``(',', ': ')`` otherwise. To get the most compact JSON representation, 152 you should specify ``(',', ':')`` to eliminate whitespace. 153 154 ``default(obj)`` is a function that should return a serializable version 155 of obj or raise TypeError. The default simply raises TypeError. 156 157 If *sort_keys* is true (default: ``False``), then the output of 158 dictionaries will be sorted by key. 159 160 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the 161 ``.default()`` method to serialize additional types), specify it with 162 the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. 163 164 """ 165 # cached encoder 166 if (not skipkeys and ensure_ascii and 167 check_circular and allow_nan and 168 cls is None and indent is None and separators is None and 169 default is None and not sort_keys and not kw): 170 iterable = _default_encoder.iterencode(obj) 171 else: 172 if cls is None: 173 cls = JSONEncoder 174 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, 175 check_circular=check_circular, allow_nan=allow_nan, indent=indent, 176 separators=separators, 177 default=default, sort_keys=sort_keys, **kw).iterencode(obj) 178 # could accelerate with writelines in some versions of Python, at 179 # a debuggability cost 180 for chunk in iterable: 181 fp.write(chunk)
Serialize obj
as a JSON formatted stream to fp
(a
.write()
-supporting file-like object).
If skipkeys
is true then dict
keys that are not basic types
(str
, int
, float
, bool
, None
) will be skipped
instead of raising a TypeError
.
If ensure_ascii
is false, then the strings written to fp
can
contain non-ASCII characters if they appear in strings contained in
obj
. Otherwise, all such characters are escaped in JSON strings.
If check_circular
is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an OverflowError
(or worse).
If allow_nan
is false, then it will be a ValueError
to
serialize out of range float
values (nan
, inf
, -inf
)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (NaN
, Infinity
, -Infinity
).
If indent
is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. None
is the most compact
representation.
If specified, separators
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(obj)
is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If sort_keys is true (default: False
), then the output of
dictionaries will be sorted by key.
To use a custom JSONEncoder
subclass (e.g. one that overrides the
.default()
method to serialize additional types), specify it with
the cls
kwarg; otherwise JSONEncoder
is used.
184def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, 185 allow_nan=True, cls=None, indent=None, separators=None, 186 default=None, sort_keys=False, **kw): 187 """Serialize ``obj`` to a JSON formatted ``str``. 188 189 If ``skipkeys`` is true then ``dict`` keys that are not basic types 190 (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped 191 instead of raising a ``TypeError``. 192 193 If ``ensure_ascii`` is false, then the return value can contain non-ASCII 194 characters if they appear in strings contained in ``obj``. Otherwise, all 195 such characters are escaped in JSON strings. 196 197 If ``check_circular`` is false, then the circular reference check 198 for container types will be skipped and a circular reference will 199 result in an ``OverflowError`` (or worse). 200 201 If ``allow_nan`` is false, then it will be a ``ValueError`` to 202 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in 203 strict compliance of the JSON specification, instead of using the 204 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). 205 206 If ``indent`` is a non-negative integer, then JSON array elements and 207 object members will be pretty-printed with that indent level. An indent 208 level of 0 will only insert newlines. ``None`` is the most compact 209 representation. 210 211 If specified, ``separators`` should be an ``(item_separator, key_separator)`` 212 tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and 213 ``(',', ': ')`` otherwise. To get the most compact JSON representation, 214 you should specify ``(',', ':')`` to eliminate whitespace. 215 216 ``default(obj)`` is a function that should return a serializable version 217 of obj or raise TypeError. The default simply raises TypeError. 218 219 If *sort_keys* is true (default: ``False``), then the output of 220 dictionaries will be sorted by key. 221 222 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the 223 ``.default()`` method to serialize additional types), specify it with 224 the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. 225 226 """ 227 # cached encoder 228 if (not skipkeys and ensure_ascii and 229 check_circular and allow_nan and 230 cls is None and indent is None and separators is None and 231 default is None and not sort_keys and not kw): 232 return _default_encoder.encode(obj) 233 if cls is None: 234 cls = JSONEncoder 235 return cls( 236 skipkeys=skipkeys, ensure_ascii=ensure_ascii, 237 check_circular=check_circular, allow_nan=allow_nan, indent=indent, 238 separators=separators, default=default, sort_keys=sort_keys, 239 **kw).encode(obj)
Serialize obj
to a JSON formatted str
.
If skipkeys
is true then dict
keys that are not basic types
(str
, int
, float
, bool
, None
) will be skipped
instead of raising a TypeError
.
If ensure_ascii
is false, then the return value can contain non-ASCII
characters if they appear in strings contained in obj
. Otherwise, all
such characters are escaped in JSON strings.
If check_circular
is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an OverflowError
(or worse).
If allow_nan
is false, then it will be a ValueError
to
serialize out of range float
values (nan
, inf
, -inf
) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (NaN
, Infinity
, -Infinity
).
If indent
is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. None
is the most compact
representation.
If specified, separators
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(obj)
is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If sort_keys is true (default: False
), then the output of
dictionaries will be sorted by key.
To use a custom JSONEncoder
subclass (e.g. one that overrides the
.default()
method to serialize additional types), specify it with
the cls
kwarg; otherwise JSONEncoder
is used.
275def load(fp, *, cls=None, object_hook=None, parse_float=None, 276 parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): 277 """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing 278 a JSON document) to a Python object. 279 280 ``object_hook`` is an optional function that will be called with the 281 result of any object literal decode (a ``dict``). The return value of 282 ``object_hook`` will be used instead of the ``dict``. This feature 283 can be used to implement custom decoders (e.g. JSON-RPC class hinting). 284 285 ``object_pairs_hook`` is an optional function that will be called with the 286 result of any object literal decoded with an ordered list of pairs. The 287 return value of ``object_pairs_hook`` will be used instead of the ``dict``. 288 This feature can be used to implement custom decoders. If ``object_hook`` 289 is also defined, the ``object_pairs_hook`` takes priority. 290 291 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` 292 kwarg; otherwise ``JSONDecoder`` is used. 293 """ 294 return loads(fp.read(), 295 cls=cls, object_hook=object_hook, 296 parse_float=parse_float, parse_int=parse_int, 297 parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
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.
300def loads(s, *, cls=None, object_hook=None, parse_float=None, 301 parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): 302 """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance 303 containing a JSON document) to a Python object. 304 305 ``object_hook`` is an optional function that will be called with the 306 result of any object literal decode (a ``dict``). The return value of 307 ``object_hook`` will be used instead of the ``dict``. This feature 308 can be used to implement custom decoders (e.g. JSON-RPC class hinting). 309 310 ``object_pairs_hook`` is an optional function that will be called with the 311 result of any object literal decoded with an ordered list of pairs. The 312 return value of ``object_pairs_hook`` will be used instead of the ``dict``. 313 This feature can be used to implement custom decoders. If ``object_hook`` 314 is also defined, the ``object_pairs_hook`` takes priority. 315 316 ``parse_float``, if specified, will be called with the string 317 of every JSON float to be decoded. By default this is equivalent to 318 float(num_str). This can be used to use another datatype or parser 319 for JSON floats (e.g. decimal.Decimal). 320 321 ``parse_int``, if specified, will be called with the string 322 of every JSON int to be decoded. By default this is equivalent to 323 int(num_str). This can be used to use another datatype or parser 324 for JSON integers (e.g. float). 325 326 ``parse_constant``, if specified, will be called with one of the 327 following strings: -Infinity, Infinity, NaN. 328 This can be used to raise an exception if invalid JSON numbers 329 are encountered. 330 331 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` 332 kwarg; otherwise ``JSONDecoder`` is used. 333 334 The ``encoding`` argument is ignored and deprecated since Python 3.1. 335 """ 336 if isinstance(s, str): 337 if s.startswith('\ufeff'): 338 raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)", 339 s, 0) 340 else: 341 if not isinstance(s, (bytes, bytearray)): 342 raise TypeError(f'the JSON object must be str, bytes or bytearray, ' 343 f'not {s.__class__.__name__}') 344 s = s.decode(detect_encoding(s), 'surrogatepass') 345 346 if "encoding" in kw: 347 import warnings 348 warnings.warn( 349 "'encoding' is ignored and deprecated. It will be removed in Python 3.9", 350 DeprecationWarning, 351 stacklevel=2 352 ) 353 del kw['encoding'] 354 355 if (cls is None and object_hook is None and 356 parse_int is None and parse_float is None and 357 parse_constant is None and object_pairs_hook is None and not kw): 358 return _default_decoder.decode(s) 359 if cls is None: 360 cls = JSONDecoder 361 if object_hook is not None: 362 kw['object_hook'] = object_hook 363 if object_pairs_hook is not None: 364 kw['object_pairs_hook'] = object_pairs_hook 365 if parse_float is not None: 366 kw['parse_float'] = parse_float 367 if parse_int is not None: 368 kw['parse_int'] = parse_int 369 if parse_constant is not None: 370 kw['parse_constant'] = parse_constant 371 return cls(**kw).decode(s)
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.
The encoding
argument is ignored and deprecated since Python 3.1.