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://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({'6': 7, '4': 5}, sort_keys=True, indent=4)) 58 { 59 "4": 5, 60 "6": 7 61 } 62 63Specializing JSON object encoding:: 64 65 >>> import json 66 >>> def custom_json(obj): 67 ... if isinstance(obj, complex): 68 ... return {'__complex__': True, 'real': obj.real, 'imag': obj.imag} 69 ... raise TypeError(f'Cannot serialize object of {type(obj)}') 70 ... 71 >>> json.dumps(1 + 2j, default=custom_json) 72 '{"__complex__": true, "real": 1.0, "imag": 2.0}' 73 74Decoding JSON:: 75 76 >>> import json 77 >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') 78 ['foo', {'bar': ['baz', None, 1.0, 2]}] 79 >>> json.loads('"\\"foo\\bar"') 80 '"foo\x08ar' 81 >>> from io import StringIO 82 >>> io = StringIO('["streaming API"]') 83 >>> json.load(io) 84 ['streaming API'] 85 86Specializing JSON object decoding:: 87 88 >>> import json 89 >>> def as_complex(dct): 90 ... if '__complex__' in dct: 91 ... return complex(dct['real'], dct['imag']) 92 ... return dct 93 ... 94 >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', 95 ... object_hook=as_complex) 96 (1+2j) 97 >>> import decimal 98 >>> json.loads('1.1', parse_float=decimal.Decimal) 99 Decimal('1.1') 100 101Extending :class:`JSONEncoder`:: 102 103 >>> import json 104 >>> class ComplexEncoder(json.JSONEncoder): 105 ... def default(self, obj): 106 ... if isinstance(obj, complex): 107 ... return [obj.real, obj.imag] 108 ... # Let the base class default method raise the TypeError 109 ... return super().default(obj) 110 ... 111 >>> json.dumps(2 + 1j, cls=ComplexEncoder) 112 '[2.0, 1.0]' 113 >>> ComplexEncoder().encode(2 + 1j) 114 '[2.0, 1.0]' 115 >>> list(ComplexEncoder().iterencode(2 + 1j)) 116 ['[2.0', ', 1.0', ']'] 117 118 119Using :mod:`json.tool` from the shell to validate and pretty-print: 120 121.. code-block:: shell-session 122 123 $ echo '{"json":"obj"}' | python -m json.tool 124 { 125 "json": "obj" 126 } 127 $ echo '{1.2:3.4}' | python -m json.tool 128 Expecting property name enclosed in double quotes: line 1 column 2 (char 1) 129 130See :ref:`json-commandline` for detailed documentation. 131 132.. note:: 133 134 JSON is a subset of `YAML <https://yaml.org/>`_ 1.2. The JSON produced by 135 this module's default settings (in particular, the default *separators* 136 value) is also a subset of YAML 1.0 and 1.1. This module can thus also be 137 used as a YAML serializer. 138 139.. note:: 140 141 This module's encoders and decoders preserve input and output order by 142 default. Order is only lost if the underlying containers are unordered. 143 144 145Basic Usage 146----------- 147 148.. function:: dump(obj, fp, *, skipkeys=False, ensure_ascii=True, \ 149 check_circular=True, allow_nan=True, cls=None, \ 150 indent=None, separators=None, default=None, \ 151 sort_keys=False, **kw) 152 153 Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting 154 :term:`file-like object`) using this :ref:`conversion table 155 <py-to-json-table>`. 156 157 If *skipkeys* is true (default: ``False``), then dict keys that are not 158 of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`, 159 ``None``) will be skipped instead of raising a :exc:`TypeError`. 160 161 The :mod:`json` module always produces :class:`str` objects, not 162 :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str` 163 input. 164 165 If *ensure_ascii* is true (the default), the output is guaranteed to 166 have all incoming non-ASCII characters escaped. If *ensure_ascii* is 167 false, these characters will be output as-is. 168 169 If *check_circular* is false (default: ``True``), then the circular 170 reference check for container types will be skipped and a circular reference 171 will result in a :exc:`RecursionError` (or worse). 172 173 If *allow_nan* is false (default: ``True``), then it will be a 174 :exc:`ValueError` to serialize out of range :class:`float` values (``nan``, 175 ``inf``, ``-inf``) in strict compliance of the JSON specification. 176 If *allow_nan* is true, their JavaScript equivalents (``NaN``, 177 ``Infinity``, ``-Infinity``) will be used. 178 179 If *indent* is a non-negative integer or string, then JSON array elements and 180 object members will be pretty-printed with that indent level. An indent level 181 of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) 182 selects the most compact representation. Using a positive integer indent 183 indents that many spaces per level. If *indent* is a string (such as ``"\t"``), 184 that string is used to indent each level. 185 186 .. versionchanged:: 3.2 187 Allow strings for *indent* in addition to integers. 188 189 If specified, *separators* should be an ``(item_separator, key_separator)`` 190 tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and 191 ``(',', ': ')`` otherwise. To get the most compact JSON representation, 192 you should specify ``(',', ':')`` to eliminate whitespace. 193 194 .. versionchanged:: 3.4 195 Use ``(',', ': ')`` as default if *indent* is not ``None``. 196 197 If specified, *default* should be a function that gets called for objects that 198 can't otherwise be serialized. It should return a JSON encodable version of 199 the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError` 200 is raised. 201 202 If *sort_keys* is true (default: ``False``), then the output of 203 dictionaries will be sorted by key. 204 205 To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the 206 :meth:`~JSONEncoder.default` method to serialize additional types), specify it with the 207 *cls* kwarg; otherwise :class:`JSONEncoder` is used. 208 209 .. versionchanged:: 3.6 210 All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`. 211 212 .. note:: 213 214 Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol, 215 so trying to serialize multiple objects with repeated calls to 216 :func:`dump` using the same *fp* will result in an invalid JSON file. 217 218.. function:: dumps(obj, *, skipkeys=False, ensure_ascii=True, \ 219 check_circular=True, allow_nan=True, cls=None, \ 220 indent=None, separators=None, default=None, \ 221 sort_keys=False, **kw) 222 223 Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion 224 table <py-to-json-table>`. The arguments have the same meaning as in 225 :func:`dump`. 226 227 .. note:: 228 229 Keys in key/value pairs of JSON are always of the type :class:`str`. When 230 a dictionary is converted into JSON, all the keys of the dictionary are 231 coerced to strings. As a result of this, if a dictionary is converted 232 into JSON and then back into a dictionary, the dictionary may not equal 233 the original one. That is, ``loads(dumps(x)) != x`` if x has non-string 234 keys. 235 236.. function:: load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) 237 238 Deserialize *fp* (a ``.read()``-supporting :term:`text file` or 239 :term:`binary file` containing a JSON document) to a Python object using 240 this :ref:`conversion table <json-to-py-table>`. 241 242 *object_hook* is an optional function that will be called with the result of 243 any object literal decoded (a :class:`dict`). The return value of 244 *object_hook* will be used instead of the :class:`dict`. This feature can 245 be used to implement custom decoders (e.g. `JSON-RPC 246 <https://www.jsonrpc.org>`_ class hinting). 247 248 *object_pairs_hook* is an optional function that will be called with the 249 result of any object literal decoded with an ordered list of pairs. The 250 return value of *object_pairs_hook* will be used instead of the 251 :class:`dict`. This feature can be used to implement custom decoders. If 252 *object_hook* is also defined, the *object_pairs_hook* takes priority. 253 254 .. versionchanged:: 3.1 255 Added support for *object_pairs_hook*. 256 257 *parse_float* is an optional function that will be called with the string of 258 every JSON float to be decoded. By default, this is equivalent to 259 ``float(num_str)``. This can be used to use another datatype or parser for 260 JSON floats (e.g. :class:`decimal.Decimal`). 261 262 *parse_int* is an optional function that will be called with the string of 263 every JSON int to be decoded. By default, this is equivalent to 264 ``int(num_str)``. This can be used to use another datatype or parser for 265 JSON integers (e.g. :class:`float`). 266 267 .. versionchanged:: 3.11 268 The default *parse_int* of :func:`int` now limits the maximum length of 269 the integer string via the interpreter's :ref:`integer string 270 conversion length limitation <int_max_str_digits>` to help avoid denial 271 of service attacks. 272 273 *parse_constant* is an optional function that will be called with one of the 274 following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be 275 used to raise an exception if invalid JSON numbers are encountered. 276 277 .. versionchanged:: 3.1 278 *parse_constant* doesn't get called on 'null', 'true', 'false' anymore. 279 280 To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls`` 281 kwarg; otherwise :class:`JSONDecoder` is used. Additional keyword arguments 282 will be passed to the constructor of the class. 283 284 If the data being deserialized is not a valid JSON document, a 285 :exc:`JSONDecodeError` will be raised. 286 287 .. versionchanged:: 3.6 288 All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`. 289 290 .. versionchanged:: 3.6 291 *fp* can now be a :term:`binary file`. The input encoding should be 292 UTF-8, UTF-16 or UTF-32. 293 294.. function:: loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) 295 296 Deserialize *s* (a :class:`str`, :class:`bytes` or :class:`bytearray` 297 instance containing a JSON document) to a Python object using this 298 :ref:`conversion table <json-to-py-table>`. 299 300 The other arguments have the same meaning as in :func:`load`. 301 302 If the data being deserialized is not a valid JSON document, a 303 :exc:`JSONDecodeError` will be raised. 304 305 .. versionchanged:: 3.6 306 *s* can now be of type :class:`bytes` or :class:`bytearray`. The 307 input encoding should be UTF-8, UTF-16 or UTF-32. 308 309 .. versionchanged:: 3.9 310 The keyword argument *encoding* has been removed. 311 312 313Encoders and Decoders 314--------------------- 315 316.. class:: JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None) 317 318 Simple JSON decoder. 319 320 Performs the following translations in decoding by default: 321 322 .. _json-to-py-table: 323 324 +---------------+-------------------+ 325 | JSON | Python | 326 +===============+===================+ 327 | object | dict | 328 +---------------+-------------------+ 329 | array | list | 330 +---------------+-------------------+ 331 | string | str | 332 +---------------+-------------------+ 333 | number (int) | int | 334 +---------------+-------------------+ 335 | number (real) | float | 336 +---------------+-------------------+ 337 | true | True | 338 +---------------+-------------------+ 339 | false | False | 340 +---------------+-------------------+ 341 | null | None | 342 +---------------+-------------------+ 343 344 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their 345 corresponding ``float`` values, which is outside the JSON spec. 346 347 *object_hook* is an optional function that will be called with the result of 348 every JSON object decoded and its return value will be used in place of the 349 given :class:`dict`. This can be used to provide custom deserializations 350 (e.g. to support `JSON-RPC <https://www.jsonrpc.org>`_ class hinting). 351 352 *object_pairs_hook* is an optional function that will be called with the 353 result of every JSON object decoded with an ordered list of pairs. The 354 return value of *object_pairs_hook* will be used instead of the 355 :class:`dict`. This feature can be used to implement custom decoders. If 356 *object_hook* is also defined, the *object_pairs_hook* takes priority. 357 358 .. versionchanged:: 3.1 359 Added support for *object_pairs_hook*. 360 361 *parse_float* is an optional function that will be called with the string of 362 every JSON float to be decoded. By default, this is equivalent to 363 ``float(num_str)``. This can be used to use another datatype or parser for 364 JSON floats (e.g. :class:`decimal.Decimal`). 365 366 *parse_int* is an optional function that will be called with the string of 367 every JSON int to be decoded. By default, this is equivalent to 368 ``int(num_str)``. This can be used to use another datatype or parser for 369 JSON integers (e.g. :class:`float`). 370 371 *parse_constant* is an optional function that will be called with one of the 372 following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be 373 used to raise an exception if invalid JSON numbers are encountered. 374 375 If *strict* is false (``True`` is the default), then control characters 376 will be allowed inside strings. Control characters in this context are 377 those with character codes in the 0--31 range, including ``'\t'`` (tab), 378 ``'\n'``, ``'\r'`` and ``'\0'``. 379 380 If the data being deserialized is not a valid JSON document, a 381 :exc:`JSONDecodeError` will be raised. 382 383 .. versionchanged:: 3.6 384 All parameters are now :ref:`keyword-only <keyword-only_parameter>`. 385 386 .. method:: decode(s) 387 388 Return the Python representation of *s* (a :class:`str` instance 389 containing a JSON document). 390 391 :exc:`JSONDecodeError` will be raised if the given JSON document is not 392 valid. 393 394 .. method:: raw_decode(s) 395 396 Decode a JSON document from *s* (a :class:`str` beginning with a 397 JSON document) and return a 2-tuple of the Python representation 398 and the index in *s* where the document ended. 399 400 This can be used to decode a JSON document from a string that may have 401 extraneous data at the end. 402 403 404.. class:: JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None) 405 406 Extensible JSON encoder for Python data structures. 407 408 Supports the following objects and types by default: 409 410 .. _py-to-json-table: 411 412 +----------------------------------------+---------------+ 413 | Python | JSON | 414 +========================================+===============+ 415 | dict | object | 416 +----------------------------------------+---------------+ 417 | list, tuple | array | 418 +----------------------------------------+---------------+ 419 | str | string | 420 +----------------------------------------+---------------+ 421 | int, float, int- & float-derived Enums | number | 422 +----------------------------------------+---------------+ 423 | True | true | 424 +----------------------------------------+---------------+ 425 | False | false | 426 +----------------------------------------+---------------+ 427 | None | null | 428 +----------------------------------------+---------------+ 429 430 .. versionchanged:: 3.4 431 Added support for int- and float-derived Enum classes. 432 433 To extend this to recognize other objects, subclass and implement a 434 :meth:`~JSONEncoder.default` method with another method that returns a serializable object 435 for ``o`` if possible, otherwise it should call the superclass implementation 436 (to raise :exc:`TypeError`). 437 438 If *skipkeys* is false (the default), a :exc:`TypeError` will be raised when 439 trying to encode keys that are not :class:`str`, :class:`int`, :class:`float` 440 or ``None``. If *skipkeys* is true, such items are simply 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 a :exc:`RecursionError`). 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 495 :meth:`~JSONEncoder.default` 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 super().default(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 <https://ecma-international.org/publications-and-standards/standards/ecma-404/>`_. 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, :data:`sys.stdin` and :data:`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.. option:: 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 :data:`sys.stdin`. 734 735.. option:: outfile 736 737 Write the output of the *infile* to the given *outfile*. Otherwise, write it 738 to :data:`sys.stdout`. 739 740.. option:: --sort-keys 741 742 Sort the output of dictionaries alphabetically by key. 743 744 .. versionadded:: 3.5 745 746.. option:: --no-ensure-ascii 747 748 Disable escaping of non-ascii characters, see :func:`json.dumps` for more information. 749 750 .. versionadded:: 3.9 751 752.. option:: --json-lines 753 754 Parse every input line as separate JSON object. 755 756 .. versionadded:: 3.8 757 758.. option:: --indent, --tab, --no-indent, --compact 759 760 Mutually exclusive options for whitespace control. 761 762 .. versionadded:: 3.9 763 764.. option:: -h, --help 765 766 Show the help message. 767 768 769.. rubric:: Footnotes 770 771.. [#rfc-errata] As noted in `the errata for RFC 7159 772 <https://www.rfc-editor.org/errata_search.php?rfc=7159>`_, 773 JSON permits literal U+2028 (LINE SEPARATOR) and 774 U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript 775 (as of ECMAScript Edition 5.1) does not. 776