ยปCore Development>Code coverage>Lib/json/__init__.py

Python code coverage for Lib/json/__init__.py

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