Debian Codegraph @

lib-python/3/json/__init__.py

raw symbols SCIP
1 r"""JSON (JavaScript Object Notation) <https://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 derived from a
7 version of the externally maintained simplejson library.
8
9 Encoding basic Python object hierarchies::
10
11 >>> import json
12 >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
13 '["foo", {"bar": ["baz", null, 1.0, 2]}]'
14 >>> print(json.dumps("\"foo\bar"))
15 "\"foo\bar"
16 >>> print(json.dumps('\u1234'))
17 "\u1234"
18 >>> print(json.dumps('\\'))
19 "\\"
20 >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
21 {"a": 0, "b": 0, "c": 0}
22 >>> from io import StringIO
23 >>> io = StringIO()
24 >>> json.dump(['streaming API'], io)
25 >>> io.getvalue()
26 '["streaming API"]'
27
28 Compact encoding::
29
30 >>> import json
31 >>> mydict = {'4': 5, '6': 7}
32 >>> json.dumps([1,2,3,mydict], separators=(',', ':'))
33 '[1,2,3,{"4":5,"6":7}]'
34
35 Pretty printing::
36
37 >>> import json
38 >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
39 {
40 "4": 5,
41 "6": 7
42 }
43
44 Decoding JSON::
45
46 >>> import json
47 >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]
48 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
49 True
50 >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar'
51 True
52 >>> from io import StringIO
53 >>> io = StringIO('["streaming API"]')
54 >>> json.load(io)[0] == 'streaming API'
55 True
56
57 Specializing JSON object decoding::
58
59 >>> import json
60 >>> def as_complex(dct):
61 ... if '__complex__' in dct:
62 ... return complex(dct['real'], dct['imag'])
63 ... return dct
64 ...
65 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
66 ... object_hook=as_complex)
67 (1+2j)
68 >>> from decimal import Decimal
69 >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
70 True
71
72 Specializing JSON object encoding::
73
74 >>> import json
75 >>> def encode_complex(obj):
76 ... if isinstance(obj, complex):
77 ... return [obj.real, obj.imag]
78 ... raise TypeError(f'Object of type {obj.__class__.__name__} '
79 ... f'is not JSON serializable')
80 ...
81 >>> json.dumps(2 + 1j, default=encode_complex)
82 '[2.0, 1.0]'
83 >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
84 '[2.0, 1.0]'
85 >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
86 '[2.0, 1.0]'
87
88
89 Using json.tool from the shell to validate and pretty-print::
90
91 $ echo '{"json":"obj"}' | python -m json.tool
92 {
93 "json": "obj"
94 }
95 $ echo '{ 1.2:3.4}' | python -m json.tool
96 Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
97 """
98 __version__ = '2.0.9'
99 __all__ = [
100 'dump', 'dumps', 'load', 'loads',
101 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
102 ]
103
104 __author__ = 'Bob Ippolito <[email protected]>'
105
106 try:
107 # PyPy speedup, the interface is different than CPython's _json
108 import _pypyjson
109 except ImportError:
110 _pypyjson = None
111
112 from .decoder import JSONDecoder, JSONDecodeError
113 from .encoder import JSONEncoder
114 import codecs
115
116 _default_encoder = JSONEncoder(
117 skipkeys=False,
118 ensure_ascii=True,
119 check_circular=True,
120 allow_nan=True,
121 indent=None,
122 separators=None,
123 default=None,
124 )
125
126 def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
127 allow_nan=True, cls=None, indent=None, separators=None,
128 default=None, sort_keys=False, **kw):
129 """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
130 ``.write()``-supporting file-like object).
131
132 If ``skipkeys`` is true then ``dict`` keys that are not basic types
133 (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
134 instead of raising a ``TypeError``.
135
136 If ``ensure_ascii`` is false, then the strings written to ``fp`` can
137 contain non-ASCII characters if they appear in strings contained in
138 ``obj``. Otherwise, all such characters are escaped in JSON strings.
139
140 If ``check_circular`` is false, then the circular reference check
141 for container types will be skipped and a circular reference will
142 result in an ``RecursionError`` (or worse).
143
144 If ``allow_nan`` is false, then it will be a ``ValueError`` to
145 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
146 in strict compliance of the JSON specification, instead of using the
147 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
148
149 If ``indent`` is a non-negative integer, then JSON array elements and
150 object members will be pretty-printed with that indent level. An indent
151 level of 0 will only insert newlines. ``None`` is the most compact
152 representation.
153
154 If specified, ``separators`` should be an ``(item_separator, key_separator)``
155 tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
156 ``(',', ': ')`` otherwise. To get the most compact JSON representation,
157 you should specify ``(',', ':')`` to eliminate whitespace.
158
159 ``default(obj)`` is a function that should return a serializable version
160 of obj or raise TypeError. The default simply raises TypeError.
161
162 If *sort_keys* is true (default: ``False``), then the output of
163 dictionaries will be sorted by key.
164
165 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
166 ``.default()`` method to serialize additional types), specify it with
167 the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
168
169 """
170 # cached encoder
171 if (not skipkeys and ensure_ascii and
172 check_circular and allow_nan and
173 cls is None and indent is None and separators is None and
174 default is None and not sort_keys and not kw):
175 iterable = _default_encoder.iterencode(obj)
176 else:
177 if cls is None:
178 cls = JSONEncoder
179 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
180 check_circular=check_circular, allow_nan=allow_nan, indent=indent,
181 separators=separators,
182 default=default, sort_keys=sort_keys, **kw).iterencode(obj)
183 # could accelerate with writelines in some versions of Python, at
184 # a debuggability cost
185 for chunk in iterable:
186 fp.write(chunk)
187
188
189 def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
190 allow_nan=True, cls=None, indent=None, separators=None,
191 default=None, sort_keys=False, **kw):
192 """Serialize ``obj`` to a JSON formatted ``str``.
193
194 If ``skipkeys`` is true then ``dict`` keys that are not basic types
195 (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
196 instead of raising a ``TypeError``.
197
198 If ``ensure_ascii`` is false, then the return value can contain non-ASCII
199 characters if they appear in strings contained in ``obj``. Otherwise, all
200 such characters are escaped in JSON strings.
201
202 If ``check_circular`` is false, then the circular reference check
203 for container types will be skipped and a circular reference will
204 result in an ``RecursionError`` (or worse).
205
206 If ``allow_nan`` is false, then it will be a ``ValueError`` to
207 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
208 strict compliance of the JSON specification, instead of using the
209 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
210
211 If ``indent`` is a non-negative integer, then JSON array elements and
212 object members will be pretty-printed with that indent level. An indent
213 level of 0 will only insert newlines. ``None`` is the most compact
214 representation.
215
216 If specified, ``separators`` should be an ``(item_separator, key_separator)``
217 tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
218 ``(',', ': ')`` otherwise. To get the most compact JSON representation,
219 you should specify ``(',', ':')`` to eliminate whitespace.
220
221 ``default(obj)`` is a function that should return a serializable version
222 of obj or raise TypeError. The default simply raises TypeError.
223
224 If *sort_keys* is true (default: ``False``), then the output of
225 dictionaries will be sorted by key.
226
227 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
228 ``.default()`` method to serialize additional types), specify it with
229 the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
230
231 """
232 # cached encoder
233 if (not skipkeys and ensure_ascii and
234 check_circular and allow_nan and
235 cls is None and indent is None and separators is None and
236 default is None and not sort_keys and not kw):
237 return _default_encoder.encode(obj)
238 if cls is None:
239 cls = JSONEncoder
240 return cls(
241 skipkeys=skipkeys, ensure_ascii=ensure_ascii,
242 check_circular=check_circular, allow_nan=allow_nan, indent=indent,
243 separators=separators, default=default, sort_keys=sort_keys,
244 **kw).encode(obj)
245
246
247 _default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None)
248
249
250 def detect_encoding(b):
251 bstartswith = b.startswith
252 if bstartswith((codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE)):
253 return 'utf-32'
254 if bstartswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
255 return 'utf-16'
256 if bstartswith(codecs.BOM_UTF8):
257 return 'utf-8-sig'
258
259 if len(b) >= 4:
260 if not b[0]:
261 # 00 00 -- -- - utf-32-be
262 # 00 XX -- -- - utf-16-be
263 return 'utf-16-be' if b[1] else 'utf-32-be'
264 if not b[1]:
265 # XX 00 00 00 - utf-32-le
266 # XX 00 00 XX - utf-16-le
267 # XX 00 XX -- - utf-16-le
268 return 'utf-16-le' if b[2] or b[3] else 'utf-32-le'
269 elif len(b) == 2:
270 if not b[0]:
271 # 00 XX - utf-16-be
272 return 'utf-16-be'
273 if not b[1]:
274 # XX 00 - utf-16-le
275 return 'utf-16-le'
276 # default
277 return 'utf-8'
278
279
280 def load(fp, *, cls=None, object_hook=None, parse_float=None,
281 parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
282 """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
283 a JSON document) to a Python object.
284
285 ``object_hook`` is an optional function that will be called with the
286 result of any object literal decode (a ``dict``). The return value of
287 ``object_hook`` will be used instead of the ``dict``. This feature
288 can be used to implement custom decoders (e.g. JSON-RPC class hinting).
289
290 ``object_pairs_hook`` is an optional function that will be called with the
291 result of any object literal decoded with an ordered list of pairs. The
292 return value of ``object_pairs_hook`` will be used instead of the ``dict``.
293 This feature can be used to implement custom decoders. If ``object_hook``
294 is also defined, the ``object_pairs_hook`` takes priority.
295
296 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
297 kwarg; otherwise ``JSONDecoder`` is used.
298 """
299 return loads(fp.read(),
300 cls=cls, object_hook=object_hook,
301 parse_float=parse_float, parse_int=parse_int,
302 parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
303
304
305 def loads(s, *, cls=None, object_hook=None, parse_float=None,
306 parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
307 """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
308 containing a JSON document) to a Python object.
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. If ``object_hook``
319 is also defined, the ``object_pairs_hook`` takes priority.
320
321 ``parse_float``, if specified, will be called with the string
322 of every JSON float to be decoded. By default this is equivalent to
323 float(num_str). This can be used to use another datatype or parser
324 for JSON floats (e.g. decimal.Decimal).
325
326 ``parse_int``, if specified, will be called with the string
327 of every JSON int to be decoded. By default this is equivalent to
328 int(num_str). This can be used to use another datatype or parser
329 for JSON integers (e.g. float).
330
331 ``parse_constant``, if specified, will be called with one of the
332 following strings: -Infinity, Infinity, NaN.
333 This can be used to raise an exception if invalid JSON numbers
334 are encountered.
335
336 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
337 kwarg; otherwise ``JSONDecoder`` is used.
338 """
339 if isinstance(s, str):
340 if s.startswith('\ufeff'):
341 raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
342 s, 0)
343 else:
344 if not isinstance(s, (bytes, bytearray)):
345 raise TypeError(f'the JSON object must be str, bytes or bytearray, '
346 f'not {s.__class__.__name__}')
347 s = s.decode(detect_encoding(s), 'surrogatepass')
348
349 if (cls is None and object_hook is None and
350 parse_int is None and parse_float is None and
351 parse_constant is None and object_pairs_hook is None and not kw):
352 return (_pypyjson.loads(s, JSONDecodeError)
353 if _pypyjson else _default_decoder.decode(s))
354 if cls is None:
355 cls = JSONDecoder
356 if object_hook is not None:
357 kw['object_hook'] = object_hook
358 if object_pairs_hook is not None:
359 kw['object_pairs_hook'] = object_pairs_hook
360 if parse_float is not None:
361 kw['parse_float'] = parse_float
362 if parse_int is not None:
363 kw['parse_int'] = parse_int
364 if parse_constant is not None:
365 kw['parse_constant'] = parse_constant
366 return cls(**kw).decode(s)