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