|
1 | | -:mod:`!json` --- JSON encoder and decoder |
| 1 | +:mod:`!json` --- JSON encoder and decoder |
2 | 2 | ========================================= |
3 | 3 |
|
4 | 4 | .. module:: json |
@@ -99,21 +99,22 @@ Specializing JSON object decoding:: |
99 | 99 | Decimal('1.1') |
100 | 100 |
|
101 | 101 | Extending :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', ']'] |
| 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 | + |
117 | 118 |
|
118 | 119 | Using :mod:`json` from the shell to validate and pretty-print: |
119 | 120 |
|
@@ -229,6 +230,12 @@ Basic Usage |
229 | 230 | If ``True``, dictionaries will be outputted sorted by key. |
230 | 231 | Default ``False``. |
231 | 232 |
|
| 233 | + .. versionchanged:: 3.2 |
| 234 | + Allow strings for *indent* in addition to integers. |
| 235 | + |
| 236 | + .. versionchanged:: 3.4 |
| 237 | + Use ``(',', ': ')`` as default if *indent* is not ``None``. |
| 238 | + |
232 | 239 | .. versionchanged:: 3.6 |
233 | 240 | All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
234 | 241 |
|
@@ -257,11 +264,198 @@ Basic Usage |
257 | 264 | the original one. That is, ``loads(dumps(x)) != x`` if x has non-string |
258 | 265 | keys. |
259 | 266 |
|
260 | | -... |
| 267 | +.. function:: load(fp, *, cls=None, object_hook=None, parse_float=None, \ |
| 268 | + parse_int=None, parse_constant=None, \ |
| 269 | + object_pairs_hook=None, **kw) |
| 270 | +
|
| 271 | + Deserialize *fp* to a Python object |
| 272 | + using the :ref:`JSON-to-Python conversion table <json-to-py-table>`. |
| 273 | + |
| 274 | + :param fp: |
| 275 | + A ``.read()``-supporting :term:`text file` or :term:`binary file` |
| 276 | + containing the JSON document to be deserialized. |
| 277 | + :type fp: :term:`file-like object` |
| 278 | + |
| 279 | + :param cls: |
| 280 | + If set, a custom JSON decoder. |
| 281 | + Additional keyword arguments to :func:`!load` |
| 282 | + will be passed to the constructor of *cls*. |
| 283 | + If ``None`` (the default), :class:`!JSONDecoder` is used. |
| 284 | + :type cls: a :class:`JSONDecoder` subclass |
| 285 | + |
| 286 | + :param object_hook: |
| 287 | + If set, a function that is called with the result of |
| 288 | + any object literal decoded (a :class:`dict`). |
| 289 | + The return value of this function will be used |
| 290 | + instead of the :class:`dict`. |
| 291 | + This feature can be used to implement custom decoders, |
| 292 | + for example `JSON-RPC <https://www.jsonrpc.org>`_ class hinting. |
| 293 | + Default ``None``. |
| 294 | + :type object_hook: :term:`callable` | None |
| 295 | + |
| 296 | + :param object_pairs_hook: |
| 297 | + If set, a function that is called with the result of |
| 298 | + any object literal decoded with an ordered list of pairs. |
| 299 | + The return value of this function will be used |
| 300 | + instead of the :class:`dict`. |
| 301 | + This feature can be used to implement custom decoders. |
| 302 | + If *object_hook* is also set, *object_pairs_hook* takes priority. |
| 303 | + Default ``None``. |
| 304 | + :type object_pairs_hook: :term:`callable` | None |
| 305 | + |
| 306 | + :param parse_float: |
| 307 | + If set, a function that is called with |
| 308 | + the string of every JSON float to be decoded. |
| 309 | + If ``None`` (the default), it is equivalent to ``float(num_str)``. |
| 310 | + This can be used to parse JSON floats into custom datatypes, |
| 311 | + for example :class:`decimal.Decimal`. |
| 312 | + :type parse_float: :term:`callable` | None |
| 313 | + |
| 314 | + :param parse_int: |
| 315 | + If set, a function that is called with |
| 316 | + the string of every JSON int to be decoded. |
| 317 | + If ``None`` (the default), it is equivalent to ``int(num_str)``. |
| 318 | + This can be used to parse JSON integers into custom datatypes, |
| 319 | + for example :class:`float`. |
| 320 | + :type parse_int: :term:`callable` | None |
| 321 | + |
| 322 | + :param parse_constant: |
| 323 | + If set, a function that is called with one of the following strings: |
| 324 | + ``'-Infinity'``, ``'Infinity'``, or ``'NaN'``. |
| 325 | + This can be used to raise an exception |
| 326 | + if invalid JSON numbers are encountered. |
| 327 | + Default ``None``. |
| 328 | + :type parse_constant: :term:`callable` | None |
| 329 | + |
| 330 | + :raises JSONDecodeError: |
| 331 | + When the data being deserialized is not a valid JSON document. |
| 332 | + |
| 333 | + :raises UnicodeDecodeError: |
| 334 | + When the data being deserialized does not contain |
| 335 | + UTF-8, UTF-16 or UTF-32 encoded data. |
| 336 | + |
| 337 | + .. versionchanged:: 3.1 |
| 338 | + |
| 339 | + * Added the optional *object_pairs_hook* parameter. |
| 340 | + * *parse_constant* doesn't get called on 'null', 'true', 'false' anymore. |
| 341 | + |
| 342 | + .. versionchanged:: 3.6 |
| 343 | + |
| 344 | + * All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
| 345 | + * *fp* can now be a :term:`binary file`. |
| 346 | + The input encoding should be UTF-8, UTF-16 or UTF-32. |
| 347 | + |
| 348 | + .. versionchanged:: 3.11 |
| 349 | + The default *parse_int* of :func:`int` now limits the maximum length of |
| 350 | + the integer string via the interpreter's :ref:`integer string |
| 351 | + conversion length limitation <int_max_str_digits>` to help avoid denial |
| 352 | + of service attacks. |
| 353 | + |
| 354 | +.. function:: loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) |
| 355 | + |
| 356 | + Identical to :func:`load`, but instead of a file-like object, |
| 357 | + deserialize *s* (a :class:`str`, :class:`bytes` or :class:`bytearray` |
| 358 | + instance containing a JSON document) to a Python object using this |
| 359 | + :ref:`conversion table <json-to-py-table>`. |
| 360 | + |
| 361 | + .. versionchanged:: 3.6 |
| 362 | + *s* can now be of type :class:`bytes` or :class:`bytearray`. The |
| 363 | + input encoding should be UTF-8, UTF-16 or UTF-32. |
| 364 | + |
| 365 | + .. versionchanged:: 3.9 |
| 366 | + The keyword argument *encoding* has been removed. |
| 367 | + |
261 | 368 |
|
262 | 369 | Encoders and Decoders |
263 | 370 | --------------------- |
264 | 371 |
|
| 372 | +.. class:: JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None) |
| 373 | + |
| 374 | + Simple JSON decoder. |
| 375 | + |
| 376 | + Performs the following translations in decoding by default: |
| 377 | + |
| 378 | + .. _json-to-py-table: |
| 379 | + |
| 380 | + +---------------+-------------------+ |
| 381 | + | JSON | Python | |
| 382 | + +===============+===================+ |
| 383 | + | object | dict | |
| 384 | + +---------------+-------------------+ |
| 385 | + | array | list | |
| 386 | + +---------------+-------------------+ |
| 387 | + | string | str | |
| 388 | + +---------------+-------------------+ |
| 389 | + | number (int) | int | |
| 390 | + +---------------+-------------------+ |
| 391 | + | number (real) | float | |
| 392 | + +---------------+-------------------+ |
| 393 | + | true | True | |
| 394 | + +---------------+-------------------+ |
| 395 | + | false | False | |
| 396 | + +---------------+-------------------+ |
| 397 | + | null | None | |
| 398 | + +---------------+-------------------+ |
| 399 | + |
| 400 | + It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their |
| 401 | + corresponding ``float`` values, which is outside the JSON spec. |
| 402 | + |
| 403 | + *object_hook* is an optional function that will be called with the result of |
| 404 | + every JSON object decoded and its return value will be used in place of the |
| 405 | + given :class:`dict`. This can be used to provide custom deserializations |
| 406 | + (e.g. to support `JSON-RPC <https://www.jsonrpc.org>`_ class hinting). |
| 407 | + |
| 408 | + *object_pairs_hook* is an optional function that will be called with the |
| 409 | + result of every JSON object decoded with an ordered list of pairs. The |
| 410 | + return value of *object_pairs_hook* will be used instead of the |
| 411 | + :class:`dict`. This feature can be used to implement custom decoders. If |
| 412 | + *object_hook* is also defined, the *object_pairs_hook* takes priority. |
| 413 | + |
| 414 | + .. versionchanged:: 3.1 |
| 415 | + Added support for *object_pairs_hook*. |
| 416 | + |
| 417 | + *parse_float* is an optional function that will be called with the string of |
| 418 | + every JSON float to be decoded. By default, this is equivalent to |
| 419 | + ``float(num_str)``. This can be used to use another datatype or parser for |
| 420 | + JSON floats (e.g. :class:`decimal.Decimal`). |
| 421 | + |
| 422 | + *parse_int* is an optional function that will be called with the string of |
| 423 | + every JSON int to be decoded. By default, this is equivalent to |
| 424 | + ``int(num_str)``. This can be used to use another datatype or parser for |
| 425 | + JSON integers (e.g. :class:`float`). |
| 426 | + |
| 427 | + *parse_constant* is an optional function that will be called with one of the |
| 428 | + following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be |
| 429 | + used to raise an exception if invalid JSON numbers are encountered. |
| 430 | + |
| 431 | + If *strict* is false (``True`` is the default), then control characters |
| 432 | + will be allowed inside strings. Control characters in this context are |
| 433 | + those with character codes in the 0--31 range, including ``'\t'`` (tab), |
| 434 | + ``'\n'``, ``'\r'`` and ``'\0'``. |
| 435 | + |
| 436 | + If the data being deserialized is not a valid JSON document, a |
| 437 | + :exc:`JSONDecodeError` will be raised. |
| 438 | + |
| 439 | + .. versionchanged:: 3.6 |
| 440 | + All parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
| 441 | + |
| 442 | + .. method:: decode(s) |
| 443 | + |
| 444 | + Return the Python representation of *s* (a :class:`str` instance |
| 445 | + containing a JSON document). |
| 446 | + |
| 447 | + :exc:`JSONDecodeError` will be raised if the given JSON document is not |
| 448 | + valid. |
| 449 | + |
| 450 | + .. method:: raw_decode(s) |
| 451 | + |
| 452 | + Decode a JSON document from *s* (a :class:`str` beginning with a |
| 453 | + JSON document) and return a 2-tuple of the Python representation |
| 454 | + and the index in *s* where the document ended. |
| 455 | + |
| 456 | + This can be used to decode a JSON document from a string that may have |
| 457 | + extraneous data at the end. |
| 458 | + |
265 | 459 | .. class:: JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None, arr_oneline=False) |
266 | 460 |
|
267 | 461 | Extensible JSON encoder for Python data structures. |
@@ -293,7 +487,7 @@ Encoders and Decoders |
293 | 487 |
|
294 | 488 | To extend this to recognize other objects, subclass and implement a |
295 | 489 | :meth:`~JSONEncoder.default` method with another method that returns a serializable object |
296 | | - for *o* if possible, otherwise it should call the superclass implementation |
| 490 | + for ``o`` if possible, otherwise it should call the superclass implementation |
297 | 491 | (to raise :exc:`TypeError`). |
298 | 492 |
|
299 | 493 | If *skipkeys* is false (the default), a :exc:`TypeError` will be raised when |
@@ -336,14 +530,22 @@ Encoders and Decoders |
336 | 530 |
|
337 | 531 | .. versionchanged:: 3.4 |
338 | 532 | Use ``(',', ': ')`` as default if *indent* is not ``None``. |
339 | | - |
340 | | - :param default: See :func:`dump`. |
| 533 | + |
| 534 | + If specified, *default* should be a function that gets called for objects that |
| 535 | + can't otherwise be serialized. It should return a JSON encodable version of |
| 536 | + the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError` |
| 537 | + is raised. |
| 538 | + |
341 | 539 | :param bool arr_oneline: |
342 | 540 | **New in this release.** |
343 | 541 | When ``True``, JSON arrays (lists and tuples) are rendered on a single line, |
344 | 542 | even if an *indent* level is specified. This option allows for a more compact |
345 | 543 | representation of array data while still enabling pretty-printing of objects. |
346 | 544 | Default is ``False``. |
| 545 | + |
| 546 | + .. versionchanged:: 3.6 |
| 547 | + All parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
| 548 | + |
347 | 549 |
|
348 | 550 | .. method:: default(o) |
349 | 551 |
|
@@ -382,6 +584,7 @@ Encoders and Decoders |
382 | 584 | for chunk in json.JSONEncoder().iterencode(bigobject): |
383 | 585 | mysocket.write(chunk) |
384 | 586 |
|
| 587 | + |
385 | 588 | Exceptions |
386 | 589 | ---------- |
387 | 590 |
|
@@ -637,4 +840,4 @@ Command-line options |
637 | 840 | <https://www.rfc-editor.org/errata_search.php?rfc=7159>`_, |
638 | 841 | JSON permits literal U+2028 (LINE SEPARATOR) and |
639 | 842 | U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript |
640 | | - (as of ECMAScript Edition 5.1) does not. |
| 843 | + (as of ECMAScript Edition 5.1) does not. |
0 commit comments