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