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