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