• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`json` --- JSON encoder and decoder
2========================================
3
4.. module:: json
5   :synopsis: Encode and decode the JSON format.
6
7.. moduleauthor:: Bob Ippolito <bob@redivi.com>
8.. sectionauthor:: Bob Ippolito <bob@redivi.com>
9
10**Source code:** :source:`Lib/json/__init__.py`
11
12--------------
13
14`JSON (JavaScript Object Notation) <http://json.org>`_, specified by
15:rfc:`7159` (which obsoletes :rfc:`4627`) and by
16`ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_,
17is a lightweight data interchange format inspired by
18`JavaScript <https://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax
19(although it is not a strict subset of JavaScript [#rfc-errata]_ ).
20
21.. warning::
22   Be cautious when parsing JSON data from untrusted sources. A malicious
23   JSON string may cause the decoder to consume considerable CPU and memory
24   resources. Limiting the size of data to be parsed is recommended.
25
26:mod:`json` exposes an API familiar to users of the standard library
27:mod:`marshal` and :mod:`pickle` modules.
28
29Encoding basic Python object hierarchies::
30
31    >>> import json
32    >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
33    '["foo", {"bar": ["baz", null, 1.0, 2]}]'
34    >>> print(json.dumps("\"foo\bar"))
35    "\"foo\bar"
36    >>> print(json.dumps('\u1234'))
37    "\u1234"
38    >>> print(json.dumps('\\'))
39    "\\"
40    >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
41    {"a": 0, "b": 0, "c": 0}
42    >>> from io import StringIO
43    >>> io = StringIO()
44    >>> json.dump(['streaming API'], io)
45    >>> io.getvalue()
46    '["streaming API"]'
47
48Compact encoding::
49
50    >>> import json
51    >>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
52    '[1,2,3,{"4":5,"6":7}]'
53
54Pretty printing::
55
56    >>> import json
57    >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
58    {
59        "4": 5,
60        "6": 7
61    }
62
63Decoding JSON::
64
65    >>> import json
66    >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
67    ['foo', {'bar': ['baz', None, 1.0, 2]}]
68    >>> json.loads('"\\"foo\\bar"')
69    '"foo\x08ar'
70    >>> from io import StringIO
71    >>> io = StringIO('["streaming API"]')
72    >>> json.load(io)
73    ['streaming API']
74
75Specializing JSON object decoding::
76
77    >>> import json
78    >>> def as_complex(dct):
79    ...     if '__complex__' in dct:
80    ...         return complex(dct['real'], dct['imag'])
81    ...     return dct
82    ...
83    >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
84    ...     object_hook=as_complex)
85    (1+2j)
86    >>> import decimal
87    >>> json.loads('1.1', parse_float=decimal.Decimal)
88    Decimal('1.1')
89
90Extending :class:`JSONEncoder`::
91
92    >>> import json
93    >>> class ComplexEncoder(json.JSONEncoder):
94    ...     def default(self, obj):
95    ...         if isinstance(obj, complex):
96    ...             return [obj.real, obj.imag]
97    ...         # Let the base class default method raise the TypeError
98    ...         return json.JSONEncoder.default(self, obj)
99    ...
100    >>> json.dumps(2 + 1j, cls=ComplexEncoder)
101    '[2.0, 1.0]'
102    >>> ComplexEncoder().encode(2 + 1j)
103    '[2.0, 1.0]'
104    >>> list(ComplexEncoder().iterencode(2 + 1j))
105    ['[2.0', ', 1.0', ']']
106
107
108Using :mod:`json.tool` from the shell to validate and pretty-print:
109
110.. code-block:: shell-session
111
112    $ echo '{"json":"obj"}' | python -m json.tool
113    {
114        "json": "obj"
115    }
116    $ echo '{1.2:3.4}' | python -m json.tool
117    Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
118
119See :ref:`json-commandline` for detailed documentation.
120
121.. note::
122
123   JSON is a subset of `YAML <http://yaml.org/>`_ 1.2.  The JSON produced by
124   this module's default settings (in particular, the default *separators*
125   value) is also a subset of YAML 1.0 and 1.1.  This module can thus also be
126   used as a YAML serializer.
127
128.. note::
129
130   This module's encoders and decoders preserve input and output order by
131   default.  Order is only lost if the underlying containers are unordered.
132
133   Prior to Python 3.7, :class:`dict` was not guaranteed to be ordered, so
134   inputs and outputs were typically scrambled unless
135   :class:`collections.OrderedDict` was specifically requested.  Starting
136   with Python 3.7, the regular :class:`dict` became order preserving, so
137   it is no longer necessary to specify :class:`collections.OrderedDict` for
138   JSON generation and parsing.
139
140
141Basic Usage
142-----------
143
144.. function:: dump(obj, fp, *, skipkeys=False, ensure_ascii=True, \
145                   check_circular=True, allow_nan=True, cls=None, \
146                   indent=None, separators=None, default=None, \
147                   sort_keys=False, **kw)
148
149   Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
150   :term:`file-like object`) using this :ref:`conversion table
151   <py-to-json-table>`.
152
153   If *skipkeys* is true (default: ``False``), then dict keys that are not
154   of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`,
155   ``None``) will be skipped instead of raising a :exc:`TypeError`.
156
157   The :mod:`json` module always produces :class:`str` objects, not
158   :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str`
159   input.
160
161   If *ensure_ascii* is true (the default), the output is guaranteed to
162   have all incoming non-ASCII characters escaped.  If *ensure_ascii* is
163   false, these characters will be output as-is.
164
165   If *check_circular* is false (default: ``True``), then the circular
166   reference check for container types will be skipped and a circular reference
167   will result in an :exc:`OverflowError` (or worse).
168
169   If *allow_nan* is false (default: ``True``), then it will be a
170   :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
171   ``inf``, ``-inf``) in strict compliance of the JSON specification.
172   If *allow_nan* is true, their JavaScript equivalents (``NaN``,
173   ``Infinity``, ``-Infinity``) will be used.
174
175   If *indent* is a non-negative integer or string, then JSON array elements and
176   object members will be pretty-printed with that indent level.  An indent level
177   of 0, negative, or ``""`` will only insert newlines.  ``None`` (the default)
178   selects the most compact representation. Using a positive integer indent
179   indents that many spaces per level.  If *indent* is a string (such as ``"\t"``),
180   that string is used to indent each level.
181
182   .. versionchanged:: 3.2
183      Allow strings for *indent* in addition to integers.
184
185   If specified, *separators* should be an ``(item_separator, key_separator)``
186   tuple.  The default is ``(', ', ': ')`` if *indent* is ``None`` and
187   ``(',', ': ')`` otherwise.  To get the most compact JSON representation,
188   you should specify ``(',', ':')`` to eliminate whitespace.
189
190   .. versionchanged:: 3.4
191      Use ``(',', ': ')`` as default if *indent* is not ``None``.
192
193   If specified, *default* should be a function that gets called for objects that
194   can't otherwise be serialized.  It should return a JSON encodable version of
195   the object or raise a :exc:`TypeError`.  If not specified, :exc:`TypeError`
196   is raised.
197
198   If *sort_keys* is true (default: ``False``), then the output of
199   dictionaries will be sorted by key.
200
201   To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
202   :meth:`default` method to serialize additional types), specify it with the
203   *cls* kwarg; otherwise :class:`JSONEncoder` is used.
204
205   .. versionchanged:: 3.6
206      All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`.
207
208   .. note::
209
210      Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol,
211      so trying to serialize multiple objects with repeated calls to
212      :func:`dump` using the same *fp* will result in an invalid JSON file.
213
214.. function:: dumps(obj, *, skipkeys=False, ensure_ascii=True, \
215                    check_circular=True, allow_nan=True, cls=None, \
216                    indent=None, separators=None, default=None, \
217                    sort_keys=False, **kw)
218
219   Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion
220   table <py-to-json-table>`.  The arguments have the same meaning as in
221   :func:`dump`.
222
223   .. note::
224
225      Keys in key/value pairs of JSON are always of the type :class:`str`. When
226      a dictionary is converted into JSON, all the keys of the dictionary are
227      coerced to strings. As a result of this, if a dictionary is converted
228      into JSON and then back into a dictionary, the dictionary may not equal
229      the original one. That is, ``loads(dumps(x)) != x`` if x has non-string
230      keys.
231
232.. function:: load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
233
234   Deserialize *fp* (a ``.read()``-supporting :term:`text file` or
235   :term:`binary file` containing a JSON document) to a Python object using
236   this :ref:`conversion table <json-to-py-table>`.
237
238   *object_hook* is an optional function that will be called with the result of
239   any object literal decoded (a :class:`dict`).  The return value of
240   *object_hook* will be used instead of the :class:`dict`.  This feature can be used
241   to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_
242   class hinting).
243
244   *object_pairs_hook* is an optional function that will be called with the
245   result of any object literal decoded with an ordered list of pairs.  The
246   return value of *object_pairs_hook* will be used instead of the
247   :class:`dict`.  This feature can be used to implement custom decoders.
248   If *object_hook* is also defined, the *object_pairs_hook* takes priority.
249
250   .. versionchanged:: 3.1
251      Added support for *object_pairs_hook*.
252
253   *parse_float*, if specified, will be called with the string of every JSON
254   float to be decoded.  By default, this is equivalent to ``float(num_str)``.
255   This can be used to use another datatype or parser for JSON floats
256   (e.g. :class:`decimal.Decimal`).
257
258   *parse_int*, if specified, will be called with the string of every JSON int
259   to be decoded.  By default, this is equivalent to ``int(num_str)``.  This can
260   be used to use another datatype or parser for JSON integers
261   (e.g. :class:`float`).
262
263   .. versionchanged:: 3.8.2
264      The default *parse_int* of :func:`int` now limits the maximum length of
265      the integer string via the interpreter's :ref:`integer string
266      conversion length limitation <int_max_str_digits>` to help avoid denial
267      of service attacks.
268
269   *parse_constant*, if specified, will be called with one of the following
270   strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
271   This can be used to raise an exception if invalid JSON numbers
272   are encountered.
273
274   .. versionchanged:: 3.1
275      *parse_constant* doesn't get called on 'null', 'true', 'false' anymore.
276
277   To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
278   kwarg; otherwise :class:`JSONDecoder` is used.  Additional keyword arguments
279   will be passed to the constructor of the class.
280
281   If the data being deserialized is not a valid JSON document, a
282   :exc:`JSONDecodeError` will be raised.
283
284   .. versionchanged:: 3.6
285      All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`.
286
287   .. versionchanged:: 3.6
288      *fp* can now be a :term:`binary file`. The input encoding should be
289      UTF-8, UTF-16 or UTF-32.
290
291.. function:: loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
292
293   Deserialize *s* (a :class:`str`, :class:`bytes` or :class:`bytearray`
294   instance containing a JSON document) to a Python object using this
295   :ref:`conversion table <json-to-py-table>`.
296
297   The other arguments have the same meaning as in :func:`load`, except
298   *encoding* which is ignored and deprecated since Python 3.1.
299
300   If the data being deserialized is not a valid JSON document, a
301   :exc:`JSONDecodeError` will be raised.
302
303   .. deprecated-removed:: 3.1 3.9
304      *encoding* keyword argument.
305
306   .. versionchanged:: 3.6
307      *s* can now be of type :class:`bytes` or :class:`bytearray`. The
308      input encoding should be UTF-8, UTF-16 or UTF-32.
309
310
311Encoders and Decoders
312---------------------
313
314.. class:: JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
315
316   Simple JSON decoder.
317
318   Performs the following translations in decoding by default:
319
320   .. _json-to-py-table:
321
322   +---------------+-------------------+
323   | JSON          | Python            |
324   +===============+===================+
325   | object        | dict              |
326   +---------------+-------------------+
327   | array         | list              |
328   +---------------+-------------------+
329   | string        | str               |
330   +---------------+-------------------+
331   | number (int)  | int               |
332   +---------------+-------------------+
333   | number (real) | float             |
334   +---------------+-------------------+
335   | true          | True              |
336   +---------------+-------------------+
337   | false         | False             |
338   +---------------+-------------------+
339   | null          | None              |
340   +---------------+-------------------+
341
342   It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
343   corresponding ``float`` values, which is outside the JSON spec.
344
345   *object_hook*, if specified, will be called with the result of every JSON
346   object decoded and its return value will be used in place of the given
347   :class:`dict`.  This can be used to provide custom deserializations (e.g. to
348   support JSON-RPC class hinting).
349
350   *object_pairs_hook*, if specified will be called with the result of every
351   JSON object decoded with an ordered list of pairs.  The return value of
352   *object_pairs_hook* will be used instead of the :class:`dict`.  This
353   feature can be used to implement custom decoders.  If *object_hook* is also
354   defined, the *object_pairs_hook* takes priority.
355
356   .. versionchanged:: 3.1
357      Added support for *object_pairs_hook*.
358
359   *parse_float*, if specified, will be called with the string of every JSON
360   float to be decoded.  By default, this is equivalent to ``float(num_str)``.
361   This can be used to use another datatype or parser for JSON floats
362   (e.g. :class:`decimal.Decimal`).
363
364   *parse_int*, if specified, will be called with the string of every JSON int
365   to be decoded.  By default, this is equivalent to ``int(num_str)``.  This can
366   be used to use another datatype or parser for JSON integers
367   (e.g. :class:`float`).
368
369   *parse_constant*, if specified, will be called with one of the following
370   strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
371   This can be used to raise an exception if invalid JSON numbers
372   are encountered.
373
374   If *strict* is false (``True`` is the default), then control characters
375   will be allowed inside strings.  Control characters in this context are
376   those with character codes in the 0--31 range, including ``'\t'`` (tab),
377   ``'\n'``, ``'\r'`` and ``'\0'``.
378
379   If the data being deserialized is not a valid JSON document, a
380   :exc:`JSONDecodeError` will be raised.
381
382   .. versionchanged:: 3.6
383      All parameters are now :ref:`keyword-only <keyword-only_parameter>`.
384
385   .. method:: decode(s)
386
387      Return the Python representation of *s* (a :class:`str` instance
388      containing a JSON document).
389
390      :exc:`JSONDecodeError` will be raised if the given JSON document is not
391      valid.
392
393   .. method:: raw_decode(s)
394
395      Decode a JSON document from *s* (a :class:`str` beginning with a
396      JSON document) and return a 2-tuple of the Python representation
397      and the index in *s* where the document ended.
398
399      This can be used to decode a JSON document from a string that may have
400      extraneous data at the end.
401
402
403.. class:: JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
404
405   Extensible JSON encoder for Python data structures.
406
407   Supports the following objects and types by default:
408
409   .. _py-to-json-table:
410
411   +----------------------------------------+---------------+
412   | Python                                 | JSON          |
413   +========================================+===============+
414   | dict                                   | object        |
415   +----------------------------------------+---------------+
416   | list, tuple                            | array         |
417   +----------------------------------------+---------------+
418   | str                                    | string        |
419   +----------------------------------------+---------------+
420   | int, float, int- & float-derived Enums | number        |
421   +----------------------------------------+---------------+
422   | True                                   | true          |
423   +----------------------------------------+---------------+
424   | False                                  | false         |
425   +----------------------------------------+---------------+
426   | None                                   | null          |
427   +----------------------------------------+---------------+
428
429   .. versionchanged:: 3.4
430      Added support for int- and float-derived Enum classes.
431
432   To extend this to recognize other objects, subclass and implement a
433   :meth:`default` method with another method that returns a serializable object
434   for ``o`` if possible, otherwise it should call the superclass implementation
435   (to raise :exc:`TypeError`).
436
437   If *skipkeys* is false (the default), then it is a :exc:`TypeError` to
438   attempt encoding of keys that are not :class:`str`, :class:`int`,
439   :class:`float` or ``None``.  If *skipkeys* is true, such items are simply
440   skipped.
441
442   If *ensure_ascii* is true (the default), the output is guaranteed to
443   have all incoming non-ASCII characters escaped.  If *ensure_ascii* is
444   false, these characters will be output as-is.
445
446   If *check_circular* is true (the default), then lists, dicts, and custom
447   encoded objects will be checked for circular references during encoding to
448   prevent an infinite recursion (which would cause an :exc:`OverflowError`).
449   Otherwise, no such check takes place.
450
451   If *allow_nan* is true (the default), then ``NaN``, ``Infinity``, and
452   ``-Infinity`` will be encoded as such.  This behavior is not JSON
453   specification compliant, but is consistent with most JavaScript based
454   encoders and decoders.  Otherwise, it will be a :exc:`ValueError` to encode
455   such floats.
456
457   If *sort_keys* is true (default: ``False``), then the output of dictionaries
458   will be sorted by key; this is useful for regression tests to ensure that
459   JSON serializations can be compared on a day-to-day basis.
460
461   If *indent* is a non-negative integer or string, then JSON array elements and
462   object members will be pretty-printed with that indent level.  An indent level
463   of 0, negative, or ``""`` will only insert newlines.  ``None`` (the default)
464   selects the most compact representation. Using a positive integer indent
465   indents that many spaces per level.  If *indent* is a string (such as ``"\t"``),
466   that string is used to indent each level.
467
468   .. versionchanged:: 3.2
469      Allow strings for *indent* in addition to integers.
470
471   If specified, *separators* should be an ``(item_separator, key_separator)``
472   tuple.  The default is ``(', ', ': ')`` if *indent* is ``None`` and
473   ``(',', ': ')`` otherwise.  To get the most compact JSON representation,
474   you should specify ``(',', ':')`` to eliminate whitespace.
475
476   .. versionchanged:: 3.4
477      Use ``(',', ': ')`` as default if *indent* is not ``None``.
478
479   If specified, *default* should be a function that gets called for objects that
480   can't otherwise be serialized.  It should return a JSON encodable version of
481   the object or raise a :exc:`TypeError`.  If not specified, :exc:`TypeError`
482   is raised.
483
484   .. versionchanged:: 3.6
485      All parameters are now :ref:`keyword-only <keyword-only_parameter>`.
486
487
488   .. method:: default(o)
489
490      Implement this method in a subclass such that it returns a serializable
491      object for *o*, or calls the base implementation (to raise a
492      :exc:`TypeError`).
493
494      For example, to support arbitrary iterators, you could implement default
495      like this::
496
497         def default(self, o):
498            try:
499                iterable = iter(o)
500            except TypeError:
501                pass
502            else:
503                return list(iterable)
504            # Let the base class default method raise the TypeError
505            return json.JSONEncoder.default(self, o)
506
507
508   .. method:: encode(o)
509
510      Return a JSON string representation of a Python data structure, *o*.  For
511      example::
512
513        >>> json.JSONEncoder().encode({"foo": ["bar", "baz"]})
514        '{"foo": ["bar", "baz"]}'
515
516
517   .. method:: iterencode(o)
518
519      Encode the given object, *o*, and yield each string representation as
520      available.  For example::
521
522            for chunk in json.JSONEncoder().iterencode(bigobject):
523                mysocket.write(chunk)
524
525
526Exceptions
527----------
528
529.. exception:: JSONDecodeError(msg, doc, pos)
530
531   Subclass of :exc:`ValueError` with the following additional attributes:
532
533   .. attribute:: msg
534
535      The unformatted error message.
536
537   .. attribute:: doc
538
539      The JSON document being parsed.
540
541   .. attribute:: pos
542
543      The start index of *doc* where parsing failed.
544
545   .. attribute:: lineno
546
547      The line corresponding to *pos*.
548
549   .. attribute:: colno
550
551      The column corresponding to *pos*.
552
553   .. versionadded:: 3.5
554
555
556Standard Compliance and Interoperability
557----------------------------------------
558
559The JSON format is specified by :rfc:`7159` and by
560`ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_.
561This section details this module's level of compliance with the RFC.
562For simplicity, :class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and
563parameters other than those explicitly mentioned, are not considered.
564
565This module does not comply with the RFC in a strict fashion, implementing some
566extensions that are valid JavaScript but not valid JSON.  In particular:
567
568- Infinite and NaN number values are accepted and output;
569- Repeated names within an object are accepted, and only the value of the last
570  name-value pair is used.
571
572Since the RFC permits RFC-compliant parsers to accept input texts that are not
573RFC-compliant, this module's deserializer is technically RFC-compliant under
574default settings.
575
576Character Encodings
577^^^^^^^^^^^^^^^^^^^
578
579The RFC requires that JSON be represented using either UTF-8, UTF-16, or
580UTF-32, with UTF-8 being the recommended default for maximum interoperability.
581
582As permitted, though not required, by the RFC, this module's serializer sets
583*ensure_ascii=True* by default, thus escaping the output so that the resulting
584strings only contain ASCII characters.
585
586Other than the *ensure_ascii* parameter, this module is defined strictly in
587terms of conversion between Python objects and
588:class:`Unicode strings <str>`, and thus does not otherwise directly address
589the issue of character encodings.
590
591The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text,
592and this module's serializer does not add a BOM to its output.
593The RFC permits, but does not require, JSON deserializers to ignore an initial
594BOM in their input.  This module's deserializer raises a :exc:`ValueError`
595when an initial BOM is present.
596
597The RFC does not explicitly forbid JSON strings which contain byte sequences
598that don't correspond to valid Unicode characters (e.g. unpaired UTF-16
599surrogates), but it does note that they may cause interoperability problems.
600By default, this module accepts and outputs (when present in the original
601:class:`str`) code points for such sequences.
602
603
604Infinite and NaN Number Values
605^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
606
607The RFC does not permit the representation of infinite or NaN number values.
608Despite that, by default, this module accepts and outputs ``Infinity``,
609``-Infinity``, and ``NaN`` as if they were valid JSON number literal values::
610
611   >>> # Neither of these calls raises an exception, but the results are not valid JSON
612   >>> json.dumps(float('-inf'))
613   '-Infinity'
614   >>> json.dumps(float('nan'))
615   'NaN'
616   >>> # Same when deserializing
617   >>> json.loads('-Infinity')
618   -inf
619   >>> json.loads('NaN')
620   nan
621
622In the serializer, the *allow_nan* parameter can be used to alter this
623behavior.  In the deserializer, the *parse_constant* parameter can be used to
624alter this behavior.
625
626
627Repeated Names Within an Object
628^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
629
630The RFC specifies that the names within a JSON object should be unique, but
631does not mandate how repeated names in JSON objects should be handled.  By
632default, this module does not raise an exception; instead, it ignores all but
633the last name-value pair for a given name::
634
635   >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
636   >>> json.loads(weird_json)
637   {'x': 3}
638
639The *object_pairs_hook* parameter can be used to alter this behavior.
640
641
642Top-level Non-Object, Non-Array Values
643^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
644
645The old version of JSON specified by the obsolete :rfc:`4627` required that
646the top-level value of a JSON text must be either a JSON object or array
647(Python :class:`dict` or :class:`list`), and could not be a JSON null,
648boolean, number, or string value.  :rfc:`7159` removed that restriction, and
649this module does not and has never implemented that restriction in either its
650serializer or its deserializer.
651
652Regardless, for maximum interoperability, you may wish to voluntarily adhere
653to the restriction yourself.
654
655
656Implementation Limitations
657^^^^^^^^^^^^^^^^^^^^^^^^^^
658
659Some JSON deserializer implementations may set limits on:
660
661* the size of accepted JSON texts
662* the maximum level of nesting of JSON objects and arrays
663* the range and precision of JSON numbers
664* the content and maximum length of JSON strings
665
666This module does not impose any such limits beyond those of the relevant
667Python datatypes themselves or the Python interpreter itself.
668
669When serializing to JSON, beware any such limitations in applications that may
670consume your JSON.  In particular, it is common for JSON numbers to be
671deserialized into IEEE 754 double precision numbers and thus subject to that
672representation's range and precision limitations.  This is especially relevant
673when serializing Python :class:`int` values of extremely large magnitude, or
674when serializing instances of "exotic" numerical types such as
675:class:`decimal.Decimal`.
676
677
678.. _json-commandline:
679.. program:: json.tool
680
681Command Line Interface
682----------------------
683
684.. module:: json.tool
685    :synopsis: A command line to validate and pretty-print JSON.
686
687**Source code:** :source:`Lib/json/tool.py`
688
689--------------
690
691The :mod:`json.tool` module provides a simple command line interface to validate
692and pretty-print JSON objects.
693
694If the optional ``infile`` and ``outfile`` arguments are not
695specified, :attr:`sys.stdin` and :attr:`sys.stdout` will be used respectively:
696
697.. code-block:: shell-session
698
699    $ echo '{"json": "obj"}' | python -m json.tool
700    {
701        "json": "obj"
702    }
703    $ echo '{1.2:3.4}' | python -m json.tool
704    Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
705
706.. versionchanged:: 3.5
707   The output is now in the same order as the input. Use the
708   :option:`--sort-keys` option to sort the output of dictionaries
709   alphabetically by key.
710
711
712Command line options
713^^^^^^^^^^^^^^^^^^^^
714
715.. cmdoption:: infile
716
717   The JSON file to be validated or pretty-printed:
718
719   .. code-block:: shell-session
720
721      $ python -m json.tool mp_films.json
722      [
723          {
724              "title": "And Now for Something Completely Different",
725              "year": 1971
726          },
727          {
728              "title": "Monty Python and the Holy Grail",
729              "year": 1975
730          }
731      ]
732
733   If *infile* is not specified, read from :attr:`sys.stdin`.
734
735.. cmdoption:: outfile
736
737   Write the output of the *infile* to the given *outfile*. Otherwise, write it
738   to :attr:`sys.stdout`.
739
740.. cmdoption:: --sort-keys
741
742   Sort the output of dictionaries alphabetically by key.
743
744   .. versionadded:: 3.5
745
746.. cmdoption:: --json-lines
747
748   Parse every input line as separate JSON object.
749
750   .. versionadded:: 3.8
751
752.. cmdoption:: -h, --help
753
754   Show the help message.
755
756
757.. rubric:: Footnotes
758
759.. [#rfc-errata] As noted in `the errata for RFC 7159
760   <https://www.rfc-editor.org/errata_search.php?rfc=7159>`_,
761   JSON permits literal U+2028 (LINE SEPARATOR) and
762   U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript
763   (as of ECMAScript Edition 5.1) does not.
764