github.com/grumpyhome/grumpy@v0.3.1-0.20201208125205-7b775405bdf1/grumpy-runtime-src/third_party/stdlib/json/__init__.py (about) 1 r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of 2 JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data 3 interchange format. 4 5 :mod:`json` exposes an API familiar to users of the standard library 6 :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained 7 version of the :mod:`json` library contained in Python 2.6, but maintains 8 compatibility with Python 2.4 and Python 2.5 and (currently) has 9 significant performance advantages, even without using the optional C 10 extension for speedups. 11 12 Encoding basic Python object hierarchies:: 13 14 >>> import json 15 >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) 16 '["foo", {"bar": ["baz", null, 1.0, 2]}]' 17 >>> print json.dumps("\"foo\bar") 18 "\"foo\bar" 19 >>> print json.dumps(u'\u1234') 20 "\u1234" 21 >>> print json.dumps('\\') 22 "\\" 23 >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) 24 {"a": 0, "b": 0, "c": 0} 25 >>> from StringIO import StringIO 26 >>> io = StringIO() 27 >>> json.dump(['streaming API'], io) 28 >>> io.getvalue() 29 '["streaming API"]' 30 31 Compact encoding:: 32 33 >>> import json 34 >>> json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=(',',':')) 35 '[1,2,3,{"4":5,"6":7}]' 36 37 Pretty printing:: 38 39 >>> import json 40 >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, 41 ... indent=4, separators=(',', ': ')) 42 { 43 "4": 5, 44 "6": 7 45 } 46 47 Decoding JSON:: 48 49 >>> import json 50 >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] 51 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj 52 True 53 >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' 54 True 55 >>> from StringIO import StringIO 56 >>> io = StringIO('["streaming API"]') 57 >>> json.load(io)[0] == 'streaming API' 58 True 59 60 Specializing JSON object decoding:: 61 62 >>> import json 63 >>> def as_complex(dct): 64 ... if '__complex__' in dct: 65 ... return complex(dct['real'], dct['imag']) 66 ... return dct 67 ... 68 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', 69 ... object_hook=as_complex) 70 (1+2j) 71 >>> from decimal import Decimal 72 >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1') 73 True 74 75 Specializing JSON object encoding:: 76 77 >>> import json 78 >>> def encode_complex(obj): 79 ... if isinstance(obj, complex): 80 ... return [obj.real, obj.imag] 81 ... raise TypeError(repr(o) + " is not JSON serializable") 82 ... 83 >>> json.dumps(2 + 1j, default=encode_complex) 84 '[2.0, 1.0]' 85 >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) 86 '[2.0, 1.0]' 87 >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) 88 '[2.0, 1.0]' 89 90 91 Using json.tool from the shell to validate and pretty-print:: 92 93 $ echo '{"json":"obj"}' | python -m json.tool 94 { 95 "json": "obj" 96 } 97 $ echo '{ 1.2:3.4}' | python -m json.tool 98 Expecting property name enclosed in double quotes: line 1 column 3 (char 2) 99 """ 100 __version__ = '2.0.9' 101 __all__ = [ 102 'dump', 'dumps', 'load', 'loads', 103 'JSONDecoder', 'JSONEncoder', 104 ] 105 106 __author__ = 'Bob Ippolito <bob@redivi.com>' 107 108 # from .decoder import JSONDecoder 109 # from .encoder import JSONEncoder 110 import json.decoder 111 import json.encoder 112 import json_scanner 113 JSONDecoder = json.decoder.JSONDecoder 114 JSONEncoder = json.encoder.JSONEncoder 115 scanner = json_scanner 116 117 _default_encoder = JSONEncoder( 118 skipkeys=False, 119 ensure_ascii=True, 120 check_circular=True, 121 allow_nan=True, 122 indent=None, 123 separators=None, 124 encoding='utf-8', 125 default=None, 126 ) 127 128 def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, 129 allow_nan=True, cls=None, indent=None, separators=None, 130 encoding='utf-8', default=None, sort_keys=False, **kw): 131 """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a 132 ``.write()``-supporting file-like object). 133 134 If ``skipkeys`` is true then ``dict`` keys that are not basic types 135 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 136 will be skipped instead of raising a ``TypeError``. 137 138 If ``ensure_ascii`` is true (the default), all non-ASCII characters in the 139 output are escaped with ``\uXXXX`` sequences, and the result is a ``str`` 140 instance consisting of ASCII characters only. If ``ensure_ascii`` is 141 ``False``, some chunks written to ``fp`` may be ``unicode`` instances. 142 This usually happens because the input contains unicode strings or the 143 ``encoding`` parameter is used. Unless ``fp.write()`` explicitly 144 understands ``unicode`` (as in ``codecs.getwriter``) this is likely to 145 cause an error. 146 147 If ``check_circular`` is false, then the circular reference check 148 for container types will be skipped and a circular reference will 149 result in an ``OverflowError`` (or worse). 150 151 If ``allow_nan`` is false, then it will be a ``ValueError`` to 152 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) 153 in strict compliance of the JSON specification, instead of using the 154 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). 155 156 If ``indent`` is a non-negative integer, then JSON array elements and 157 object members will be pretty-printed with that indent level. An indent 158 level of 0 will only insert newlines. ``None`` is the most compact 159 representation. Since the default item separator is ``', '``, the 160 output might include trailing whitespace when ``indent`` is specified. 161 You can use ``separators=(',', ': ')`` to avoid this. 162 163 If ``separators`` is an ``(item_separator, dict_separator)`` tuple 164 then it will be used instead of the default ``(', ', ': ')`` separators. 165 ``(',', ':')`` is the most compact JSON representation. 166 167 ``encoding`` is the character encoding for str instances, default is UTF-8. 168 169 ``default(obj)`` is a function that should return a serializable version 170 of obj or raise TypeError. The default simply raises TypeError. 171 172 If *sort_keys* is ``True`` (default: ``False``), then the output of 173 dictionaries will be sorted by key. 174 175 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the 176 ``.default()`` method to serialize additional types), specify it with 177 the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. 178 179 """ 180 # cached encoder 181 if (not skipkeys and ensure_ascii and 182 check_circular and allow_nan and 183 cls is None and indent is None and separators is None and 184 encoding == 'utf-8' and default is None and not sort_keys and not kw): 185 iterable = _default_encoder.iterencode(obj) 186 else: 187 if cls is None: 188 cls = JSONEncoder 189 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, 190 check_circular=check_circular, allow_nan=allow_nan, indent=indent, 191 separators=separators, encoding=encoding, 192 default=default, sort_keys=sort_keys, **kw).iterencode(obj) 193 # could accelerate with writelines in some versions of Python, at 194 # a debuggability cost 195 for chunk in iterable: 196 fp.write(chunk) 197 198 199 def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, 200 allow_nan=True, cls=None, indent=None, separators=None, 201 encoding='utf-8', default=None, sort_keys=False, **kw): 202 """Serialize ``obj`` to a JSON formatted ``str``. 203 204 If ``skipkeys`` is true then ``dict`` keys that are not basic types 205 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 206 will be skipped instead of raising a ``TypeError``. 207 208 209 If ``ensure_ascii`` is false, all non-ASCII characters are not escaped, and 210 the return value may be a ``unicode`` instance. See ``dump`` for details. 211 212 If ``check_circular`` is false, then the circular reference check 213 for container types will be skipped and a circular reference will 214 result in an ``OverflowError`` (or worse). 215 216 If ``allow_nan`` is false, then it will be a ``ValueError`` to 217 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in 218 strict compliance of the JSON specification, instead of using the 219 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). 220 221 If ``indent`` is a non-negative integer, then JSON array elements and 222 object members will be pretty-printed with that indent level. An indent 223 level of 0 will only insert newlines. ``None`` is the most compact 224 representation. Since the default item separator is ``', '``, the 225 output might include trailing whitespace when ``indent`` is specified. 226 You can use ``separators=(',', ': ')`` to avoid this. 227 228 If ``separators`` is an ``(item_separator, dict_separator)`` tuple 229 then it will be used instead of the default ``(', ', ': ')`` separators. 230 ``(',', ':')`` is the most compact JSON representation. 231 232 ``encoding`` is the character encoding for str instances, default is UTF-8. 233 234 ``default(obj)`` is a function that should return a serializable version 235 of obj or raise TypeError. The default simply raises TypeError. 236 237 If *sort_keys* is ``True`` (default: ``False``), then the output of 238 dictionaries will be sorted by key. 239 240 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the 241 ``.default()`` method to serialize additional types), specify it with 242 the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. 243 244 """ 245 # cached encoder 246 if (not skipkeys and ensure_ascii and 247 check_circular and allow_nan and 248 cls is None and indent is None and separators is None and 249 encoding == 'utf-8' and default is None and not sort_keys and not kw): 250 return _default_encoder.encode(obj) 251 if cls is None: 252 cls = JSONEncoder 253 return cls( 254 skipkeys=skipkeys, ensure_ascii=ensure_ascii, 255 check_circular=check_circular, allow_nan=allow_nan, indent=indent, 256 separators=separators, encoding=encoding, default=default, 257 sort_keys=sort_keys, **kw).encode(obj) 258 259 260 _default_decoder = JSONDecoder(encoding=None, object_hook=None, 261 object_pairs_hook=None) 262 263 264 def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, 265 parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): 266 """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing 267 a JSON document) to a Python object. 268 269 If the contents of ``fp`` is encoded with an ASCII based encoding other 270 than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must 271 be specified. Encodings that are not ASCII based (such as UCS-2) are 272 not allowed, and should be wrapped with 273 ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` 274 object and passed to ``loads()`` 275 276 ``object_hook`` is an optional function that will be called with the 277 result of any object literal decode (a ``dict``). The return value of 278 ``object_hook`` will be used instead of the ``dict``. This feature 279 can be used to implement custom decoders (e.g. JSON-RPC class hinting). 280 281 ``object_pairs_hook`` is an optional function that will be called with the 282 result of any object literal decoded with an ordered list of pairs. The 283 return value of ``object_pairs_hook`` will be used instead of the ``dict``. 284 This feature can be used to implement custom decoders that rely on the 285 order that the key and value pairs are decoded (for example, 286 collections.OrderedDict will remember the order of insertion). If 287 ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. 288 289 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` 290 kwarg; otherwise ``JSONDecoder`` is used. 291 292 """ 293 return loads(fp.read(), 294 encoding=encoding, cls=cls, object_hook=object_hook, 295 parse_float=parse_float, parse_int=parse_int, 296 parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, 297 **kw) 298 299 300 def loads(s, encoding=None, 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`` or ``unicode`` instance containing a JSON 303 document) to a Python object. 304 305 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding 306 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name 307 must be specified. Encodings that are not ASCII based (such as UCS-2) 308 are not allowed and should be decoded to ``unicode`` first. 309 310 ``object_hook`` is an optional function that will be called with the 311 result of any object literal decode (a ``dict``). The return value of 312 ``object_hook`` will be used instead of the ``dict``. This feature 313 can be used to implement custom decoders (e.g. JSON-RPC class hinting). 314 315 ``object_pairs_hook`` is an optional function that will be called with the 316 result of any object literal decoded with an ordered list of pairs. The 317 return value of ``object_pairs_hook`` will be used instead of the ``dict``. 318 This feature can be used to implement custom decoders that rely on the 319 order that the key and value pairs are decoded (for example, 320 collections.OrderedDict will remember the order of insertion). If 321 ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. 322 323 ``parse_float``, if specified, will be called with the string 324 of every JSON float to be decoded. By default this is equivalent to 325 float(num_str). This can be used to use another datatype or parser 326 for JSON floats (e.g. decimal.Decimal). 327 328 ``parse_int``, if specified, will be called with the string 329 of every JSON int to be decoded. By default this is equivalent to 330 int(num_str). This can be used to use another datatype or parser 331 for JSON integers (e.g. float). 332 333 ``parse_constant``, if specified, will be called with one of the 334 following strings: -Infinity, Infinity, NaN, null, true, false. 335 This can be used to raise an exception if invalid JSON numbers 336 are encountered. 337 338 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` 339 kwarg; otherwise ``JSONDecoder`` is used. 340 341 """ 342 if (cls is None and encoding is None and object_hook is None and 343 parse_int is None and parse_float is None and 344 parse_constant is None and object_pairs_hook is None and not kw): 345 return _default_decoder.decode(s) 346 if cls is None: 347 cls = JSONDecoder 348 if object_hook is not None: 349 kw['object_hook'] = object_hook 350 if object_pairs_hook is not None: 351 kw['object_pairs_hook'] = object_pairs_hook 352 if parse_float is not None: 353 kw['parse_float'] = parse_float 354 if parse_int is not None: 355 kw['parse_int'] = parse_int 356 if parse_constant is not None: 357 kw['parse_constant'] = parse_constant 358 return cls(encoding=encoding, **kw).decode(s)