cpython/Lib/json/__init__.py

323 lines
12 KiB
Python
Raw Normal View History

r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`json` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of the :mod:`json` library contained in Python 2.6, but maintains
compatibility with Python 2.4 and Python 2.5 and (currently) has
significant performance advantages, even without using the optional C
extension for speedups.
Encoding basic Python object hierarchies::
>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print(json.dumps("\"foo\bar"))
"\"foo\bar"
>>> print(json.dumps('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Compact encoding::
>>> import json
>>> from collections import OrderedDict
>>> mydict = OrderedDict([('4', 5), ('6', 7)])
>>> json.dumps([1,2,3,mydict], separators=(',', ':'))
'[1,2,3,{"4":5,"6":7}]'
Pretty printing::
>>> import json
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
>>> print('\n'.join([l.rstrip() for l in s.splitlines()]))
{
"4": 5,
"6": 7
}
Decoding JSON::
>>> import json
>>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}]
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
True
>>> json.loads('"\\"foo\\bar"') == '"foo\x08ar'
True
>>> from io import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)[0] == 'streaming API'
True
Specializing JSON object decoding::
>>> import json
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
>>> from decimal import Decimal
>>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
True
Specializing JSON object encoding::
>>> import json
>>> def encode_complex(obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... raise TypeError(repr(o) + " is not JSON serializable")
...
>>> json.dumps(2 + 1j, default=encode_complex)
'[2.0, 1.0]'
>>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
'[2.0, 1.0]'
>>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
'[2.0, 1.0]'
Using json.tool from the shell to validate and pretty-print::
$ echo '{"json":"obj"}' | python -m json.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -m json.tool
Expecting property name: line 1 column 2 (char 2)
"""
__version__ = '2.0.9'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONEncoder',
]
__author__ = 'Bob Ippolito <bob@redivi.com>'
from .decoder import JSONDecoder
from .encoder import JSONEncoder
_default_encoder = JSONEncoder(
skipkeys=False,
ensure_ascii=True,
check_circular=True,
allow_nan=True,
indent=None,
separators=None,
default=None,
)
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
default=None, **kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
Merged revisions 82805-82806,83523-83527,83536,83538,83542,83546-83548,83550-83555,83558,83560 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r82805 | georg.brandl | 2010-07-11 11:42:10 +0200 (So, 11 Jul 2010) | 1 line #7935: cross-reference to ast.literal_eval() from eval() docs. ........ r82806 | georg.brandl | 2010-07-11 12:22:44 +0200 (So, 11 Jul 2010) | 1 line #9223: link to Command class reference, and move Command interface docs nearer to class docs. ........ r83523 | georg.brandl | 2010-08-02 14:06:18 +0200 (Mo, 02 Aug 2010) | 1 line #9209 and #7781: fix two crashes in pstats interactive browser. ........ r83524 | georg.brandl | 2010-08-02 14:20:23 +0200 (Mo, 02 Aug 2010) | 1 line #9428: fix running scripts from profile/cProfile with their own name and the right namespace. Same fix as for trace.py in #1690103. ........ r83525 | georg.brandl | 2010-08-02 14:36:24 +0200 (Mo, 02 Aug 2010) | 1 line Get rid of spurious "threading" entries in trace output. ........ r83526 | georg.brandl | 2010-08-02 14:40:22 +0200 (Mo, 02 Aug 2010) | 1 line Fix softspace relic. ........ r83527 | georg.brandl | 2010-08-02 14:48:46 +0200 (Mo, 02 Aug 2010) | 1 line #3821: beginnings of a trace.py unittest. ........ r83536 | georg.brandl | 2010-08-02 19:49:25 +0200 (Mo, 02 Aug 2010) | 1 line #8578: mention danger of not incref'ing weak referenced object. ........ r83538 | georg.brandl | 2010-08-02 20:10:13 +0200 (Mo, 02 Aug 2010) | 1 line #6928: fix class docs w.r.t. new metaclasses. ........ r83542 | georg.brandl | 2010-08-02 20:56:54 +0200 (Mo, 02 Aug 2010) | 1 line Move test_SimpleHTTPServer into test_httpservers. ........ r83546 | georg.brandl | 2010-08-02 21:16:34 +0200 (Mo, 02 Aug 2010) | 1 line #7973: Fix distutils options spelling. ........ r83547 | georg.brandl | 2010-08-02 21:19:26 +0200 (Mo, 02 Aug 2010) | 1 line #7386: add example that shows that trailing path separators are stripped. ........ r83548 | georg.brandl | 2010-08-02 21:23:34 +0200 (Mo, 02 Aug 2010) | 1 line #8172: how does one use a property? ........ r83550 | georg.brandl | 2010-08-02 21:32:43 +0200 (Mo, 02 Aug 2010) | 1 line #9451: strengthen warning about __*__ special name usage. ........ r83551 | georg.brandl | 2010-08-02 21:35:06 +0200 (Mo, 02 Aug 2010) | 1 line Remove XXX comment that was displayed. ........ r83552 | georg.brandl | 2010-08-02 21:36:36 +0200 (Mo, 02 Aug 2010) | 1 line #9438: clarify that constant names also cannot be assigned as attributes. ........ r83553 | georg.brandl | 2010-08-02 21:39:17 +0200 (Mo, 02 Aug 2010) | 1 line Remove redundant information. ........ r83554 | georg.brandl | 2010-08-02 21:43:05 +0200 (Mo, 02 Aug 2010) | 1 line #7280: note about nasmw.exe. ........ r83555 | georg.brandl | 2010-08-02 21:44:48 +0200 (Mo, 02 Aug 2010) | 1 line #8861: remove unused variable. ........ r83558 | georg.brandl | 2010-08-02 22:05:19 +0200 (Mo, 02 Aug 2010) | 1 line #8648: document UTF-7 codec functions. ........ r83560 | georg.brandl | 2010-08-02 22:16:18 +0200 (Mo, 02 Aug 2010) | 1 line #9087: update json docstrings -- unicode and long do not exist anymore. ........
2010-10-06 05:26:09 -03:00
(``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
instead of raising a ``TypeError``.
Merged revisions 82805-82806,83523-83527,83536,83538,83542,83546-83548,83550-83555,83558,83560 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r82805 | georg.brandl | 2010-07-11 11:42:10 +0200 (So, 11 Jul 2010) | 1 line #7935: cross-reference to ast.literal_eval() from eval() docs. ........ r82806 | georg.brandl | 2010-07-11 12:22:44 +0200 (So, 11 Jul 2010) | 1 line #9223: link to Command class reference, and move Command interface docs nearer to class docs. ........ r83523 | georg.brandl | 2010-08-02 14:06:18 +0200 (Mo, 02 Aug 2010) | 1 line #9209 and #7781: fix two crashes in pstats interactive browser. ........ r83524 | georg.brandl | 2010-08-02 14:20:23 +0200 (Mo, 02 Aug 2010) | 1 line #9428: fix running scripts from profile/cProfile with their own name and the right namespace. Same fix as for trace.py in #1690103. ........ r83525 | georg.brandl | 2010-08-02 14:36:24 +0200 (Mo, 02 Aug 2010) | 1 line Get rid of spurious "threading" entries in trace output. ........ r83526 | georg.brandl | 2010-08-02 14:40:22 +0200 (Mo, 02 Aug 2010) | 1 line Fix softspace relic. ........ r83527 | georg.brandl | 2010-08-02 14:48:46 +0200 (Mo, 02 Aug 2010) | 1 line #3821: beginnings of a trace.py unittest. ........ r83536 | georg.brandl | 2010-08-02 19:49:25 +0200 (Mo, 02 Aug 2010) | 1 line #8578: mention danger of not incref'ing weak referenced object. ........ r83538 | georg.brandl | 2010-08-02 20:10:13 +0200 (Mo, 02 Aug 2010) | 1 line #6928: fix class docs w.r.t. new metaclasses. ........ r83542 | georg.brandl | 2010-08-02 20:56:54 +0200 (Mo, 02 Aug 2010) | 1 line Move test_SimpleHTTPServer into test_httpservers. ........ r83546 | georg.brandl | 2010-08-02 21:16:34 +0200 (Mo, 02 Aug 2010) | 1 line #7973: Fix distutils options spelling. ........ r83547 | georg.brandl | 2010-08-02 21:19:26 +0200 (Mo, 02 Aug 2010) | 1 line #7386: add example that shows that trailing path separators are stripped. ........ r83548 | georg.brandl | 2010-08-02 21:23:34 +0200 (Mo, 02 Aug 2010) | 1 line #8172: how does one use a property? ........ r83550 | georg.brandl | 2010-08-02 21:32:43 +0200 (Mo, 02 Aug 2010) | 1 line #9451: strengthen warning about __*__ special name usage. ........ r83551 | georg.brandl | 2010-08-02 21:35:06 +0200 (Mo, 02 Aug 2010) | 1 line Remove XXX comment that was displayed. ........ r83552 | georg.brandl | 2010-08-02 21:36:36 +0200 (Mo, 02 Aug 2010) | 1 line #9438: clarify that constant names also cannot be assigned as attributes. ........ r83553 | georg.brandl | 2010-08-02 21:39:17 +0200 (Mo, 02 Aug 2010) | 1 line Remove redundant information. ........ r83554 | georg.brandl | 2010-08-02 21:43:05 +0200 (Mo, 02 Aug 2010) | 1 line #7280: note about nasmw.exe. ........ r83555 | georg.brandl | 2010-08-02 21:44:48 +0200 (Mo, 02 Aug 2010) | 1 line #8861: remove unused variable. ........ r83558 | georg.brandl | 2010-08-02 22:05:19 +0200 (Mo, 02 Aug 2010) | 1 line #8648: document UTF-7 codec functions. ........ r83560 | georg.brandl | 2010-08-02 22:16:18 +0200 (Mo, 02 Aug 2010) | 1 line #9087: update json docstrings -- unicode and long do not exist anymore. ........
2010-10-06 05:26:09 -03:00
If ``ensure_ascii`` is false, then the strings written to ``fp`` can
contain non-ASCII characters if they appear in strings contained in
``obj``. Otherwise, all such characters are escaped in JSON strings.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
Merged revisions 85530,85532-85534,85538-85543,85546-85548 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r85530 | georg.brandl | 2010-10-15 17:32:05 +0200 (Fr, 15 Okt 2010) | 1 line Refrain from using inline suites. ........ r85532 | georg.brandl | 2010-10-15 18:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #7771: reference to documentation of dictview methods and operations. ........ r85533 | georg.brandl | 2010-10-15 18:07:41 +0200 (Fr, 15 Okt 2010) | 1 line #9683: remove broken dead code dealing with nested arguments removed from Py3k, and update the docs and docstrings accordingly. ........ r85534 | georg.brandl | 2010-10-15 18:19:43 +0200 (Fr, 15 Okt 2010) | 1 line #9801: document how list and dict proxies created by Managers behave w.r.t. mutable items. ........ r85538 | georg.brandl | 2010-10-15 18:35:46 +0200 (Fr, 15 Okt 2010) | 1 line #7303: add documentation for useful pkgutil functions and classes. ........ r85539 | georg.brandl | 2010-10-15 18:42:14 +0200 (Fr, 15 Okt 2010) | 1 line Fix issue references. ........ r85540 | georg.brandl | 2010-10-15 18:42:37 +0200 (Fr, 15 Okt 2010) | 1 line #6798: fix wrong docs for the arguments to several trace events. ........ r85541 | georg.brandl | 2010-10-15 18:53:24 +0200 (Fr, 15 Okt 2010) | 1 line #4968: updates to inspect.is* function docs. ........ r85542 | georg.brandl | 2010-10-15 19:01:15 +0200 (Fr, 15 Okt 2010) | 1 line #7790: move table of struct_time members to the actual description of struct_time. ........ r85543 | georg.brandl | 2010-10-15 19:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #4785: document strict argument of JSONDecoder, plus add object_pairs_hook in the docstrings. ........ r85546 | georg.brandl | 2010-10-15 19:58:45 +0200 (Fr, 15 Okt 2010) | 1 line #5762: fix handling of empty namespace in minidom, which would result in AttributeError on toxml(). ........ r85547 | georg.brandl | 2010-10-15 20:00:35 +0200 (Fr, 15 Okt 2010) | 1 line #6098: Refrain from claiming DOM level 3 conformance in minidom. ........ r85548 | georg.brandl | 2010-10-15 21:46:19 +0200 (Fr, 15 Okt 2010) | 1 line #10072: assume a bit less knowledge of the FTP protocol in the ftplib docs. ........
2010-11-26 04:42:45 -04:00
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
"""
# cached encoder
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
default is None and not kw):
iterable = _default_encoder.iterencode(obj)
else:
if cls is None:
cls = JSONEncoder
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators,
default=default, **kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
for chunk in iterable:
fp.write(chunk)
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
default=None, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
Merged revisions 82805-82806,83523-83527,83536,83538,83542,83546-83548,83550-83555,83558,83560 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r82805 | georg.brandl | 2010-07-11 11:42:10 +0200 (So, 11 Jul 2010) | 1 line #7935: cross-reference to ast.literal_eval() from eval() docs. ........ r82806 | georg.brandl | 2010-07-11 12:22:44 +0200 (So, 11 Jul 2010) | 1 line #9223: link to Command class reference, and move Command interface docs nearer to class docs. ........ r83523 | georg.brandl | 2010-08-02 14:06:18 +0200 (Mo, 02 Aug 2010) | 1 line #9209 and #7781: fix two crashes in pstats interactive browser. ........ r83524 | georg.brandl | 2010-08-02 14:20:23 +0200 (Mo, 02 Aug 2010) | 1 line #9428: fix running scripts from profile/cProfile with their own name and the right namespace. Same fix as for trace.py in #1690103. ........ r83525 | georg.brandl | 2010-08-02 14:36:24 +0200 (Mo, 02 Aug 2010) | 1 line Get rid of spurious "threading" entries in trace output. ........ r83526 | georg.brandl | 2010-08-02 14:40:22 +0200 (Mo, 02 Aug 2010) | 1 line Fix softspace relic. ........ r83527 | georg.brandl | 2010-08-02 14:48:46 +0200 (Mo, 02 Aug 2010) | 1 line #3821: beginnings of a trace.py unittest. ........ r83536 | georg.brandl | 2010-08-02 19:49:25 +0200 (Mo, 02 Aug 2010) | 1 line #8578: mention danger of not incref'ing weak referenced object. ........ r83538 | georg.brandl | 2010-08-02 20:10:13 +0200 (Mo, 02 Aug 2010) | 1 line #6928: fix class docs w.r.t. new metaclasses. ........ r83542 | georg.brandl | 2010-08-02 20:56:54 +0200 (Mo, 02 Aug 2010) | 1 line Move test_SimpleHTTPServer into test_httpservers. ........ r83546 | georg.brandl | 2010-08-02 21:16:34 +0200 (Mo, 02 Aug 2010) | 1 line #7973: Fix distutils options spelling. ........ r83547 | georg.brandl | 2010-08-02 21:19:26 +0200 (Mo, 02 Aug 2010) | 1 line #7386: add example that shows that trailing path separators are stripped. ........ r83548 | georg.brandl | 2010-08-02 21:23:34 +0200 (Mo, 02 Aug 2010) | 1 line #8172: how does one use a property? ........ r83550 | georg.brandl | 2010-08-02 21:32:43 +0200 (Mo, 02 Aug 2010) | 1 line #9451: strengthen warning about __*__ special name usage. ........ r83551 | georg.brandl | 2010-08-02 21:35:06 +0200 (Mo, 02 Aug 2010) | 1 line Remove XXX comment that was displayed. ........ r83552 | georg.brandl | 2010-08-02 21:36:36 +0200 (Mo, 02 Aug 2010) | 1 line #9438: clarify that constant names also cannot be assigned as attributes. ........ r83553 | georg.brandl | 2010-08-02 21:39:17 +0200 (Mo, 02 Aug 2010) | 1 line Remove redundant information. ........ r83554 | georg.brandl | 2010-08-02 21:43:05 +0200 (Mo, 02 Aug 2010) | 1 line #7280: note about nasmw.exe. ........ r83555 | georg.brandl | 2010-08-02 21:44:48 +0200 (Mo, 02 Aug 2010) | 1 line #8861: remove unused variable. ........ r83558 | georg.brandl | 2010-08-02 22:05:19 +0200 (Mo, 02 Aug 2010) | 1 line #8648: document UTF-7 codec functions. ........ r83560 | georg.brandl | 2010-08-02 22:16:18 +0200 (Mo, 02 Aug 2010) | 1 line #9087: update json docstrings -- unicode and long do not exist anymore. ........
2010-10-06 05:26:09 -03:00
(``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped
instead of raising a ``TypeError``.
Merged revisions 82805-82806,83523-83527,83536,83538,83542,83546-83548,83550-83555,83558,83560 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r82805 | georg.brandl | 2010-07-11 11:42:10 +0200 (So, 11 Jul 2010) | 1 line #7935: cross-reference to ast.literal_eval() from eval() docs. ........ r82806 | georg.brandl | 2010-07-11 12:22:44 +0200 (So, 11 Jul 2010) | 1 line #9223: link to Command class reference, and move Command interface docs nearer to class docs. ........ r83523 | georg.brandl | 2010-08-02 14:06:18 +0200 (Mo, 02 Aug 2010) | 1 line #9209 and #7781: fix two crashes in pstats interactive browser. ........ r83524 | georg.brandl | 2010-08-02 14:20:23 +0200 (Mo, 02 Aug 2010) | 1 line #9428: fix running scripts from profile/cProfile with their own name and the right namespace. Same fix as for trace.py in #1690103. ........ r83525 | georg.brandl | 2010-08-02 14:36:24 +0200 (Mo, 02 Aug 2010) | 1 line Get rid of spurious "threading" entries in trace output. ........ r83526 | georg.brandl | 2010-08-02 14:40:22 +0200 (Mo, 02 Aug 2010) | 1 line Fix softspace relic. ........ r83527 | georg.brandl | 2010-08-02 14:48:46 +0200 (Mo, 02 Aug 2010) | 1 line #3821: beginnings of a trace.py unittest. ........ r83536 | georg.brandl | 2010-08-02 19:49:25 +0200 (Mo, 02 Aug 2010) | 1 line #8578: mention danger of not incref'ing weak referenced object. ........ r83538 | georg.brandl | 2010-08-02 20:10:13 +0200 (Mo, 02 Aug 2010) | 1 line #6928: fix class docs w.r.t. new metaclasses. ........ r83542 | georg.brandl | 2010-08-02 20:56:54 +0200 (Mo, 02 Aug 2010) | 1 line Move test_SimpleHTTPServer into test_httpservers. ........ r83546 | georg.brandl | 2010-08-02 21:16:34 +0200 (Mo, 02 Aug 2010) | 1 line #7973: Fix distutils options spelling. ........ r83547 | georg.brandl | 2010-08-02 21:19:26 +0200 (Mo, 02 Aug 2010) | 1 line #7386: add example that shows that trailing path separators are stripped. ........ r83548 | georg.brandl | 2010-08-02 21:23:34 +0200 (Mo, 02 Aug 2010) | 1 line #8172: how does one use a property? ........ r83550 | georg.brandl | 2010-08-02 21:32:43 +0200 (Mo, 02 Aug 2010) | 1 line #9451: strengthen warning about __*__ special name usage. ........ r83551 | georg.brandl | 2010-08-02 21:35:06 +0200 (Mo, 02 Aug 2010) | 1 line Remove XXX comment that was displayed. ........ r83552 | georg.brandl | 2010-08-02 21:36:36 +0200 (Mo, 02 Aug 2010) | 1 line #9438: clarify that constant names also cannot be assigned as attributes. ........ r83553 | georg.brandl | 2010-08-02 21:39:17 +0200 (Mo, 02 Aug 2010) | 1 line Remove redundant information. ........ r83554 | georg.brandl | 2010-08-02 21:43:05 +0200 (Mo, 02 Aug 2010) | 1 line #7280: note about nasmw.exe. ........ r83555 | georg.brandl | 2010-08-02 21:44:48 +0200 (Mo, 02 Aug 2010) | 1 line #8861: remove unused variable. ........ r83558 | georg.brandl | 2010-08-02 22:05:19 +0200 (Mo, 02 Aug 2010) | 1 line #8648: document UTF-7 codec functions. ........ r83560 | georg.brandl | 2010-08-02 22:16:18 +0200 (Mo, 02 Aug 2010) | 1 line #9087: update json docstrings -- unicode and long do not exist anymore. ........
2010-10-06 05:26:09 -03:00
If ``ensure_ascii`` is false, then the return value can contain non-ASCII
characters if they appear in strings contained in ``obj``. Otherwise, all
such characters are escaped in JSON strings.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
Merged revisions 85530,85532-85534,85538-85543,85546-85548 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r85530 | georg.brandl | 2010-10-15 17:32:05 +0200 (Fr, 15 Okt 2010) | 1 line Refrain from using inline suites. ........ r85532 | georg.brandl | 2010-10-15 18:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #7771: reference to documentation of dictview methods and operations. ........ r85533 | georg.brandl | 2010-10-15 18:07:41 +0200 (Fr, 15 Okt 2010) | 1 line #9683: remove broken dead code dealing with nested arguments removed from Py3k, and update the docs and docstrings accordingly. ........ r85534 | georg.brandl | 2010-10-15 18:19:43 +0200 (Fr, 15 Okt 2010) | 1 line #9801: document how list and dict proxies created by Managers behave w.r.t. mutable items. ........ r85538 | georg.brandl | 2010-10-15 18:35:46 +0200 (Fr, 15 Okt 2010) | 1 line #7303: add documentation for useful pkgutil functions and classes. ........ r85539 | georg.brandl | 2010-10-15 18:42:14 +0200 (Fr, 15 Okt 2010) | 1 line Fix issue references. ........ r85540 | georg.brandl | 2010-10-15 18:42:37 +0200 (Fr, 15 Okt 2010) | 1 line #6798: fix wrong docs for the arguments to several trace events. ........ r85541 | georg.brandl | 2010-10-15 18:53:24 +0200 (Fr, 15 Okt 2010) | 1 line #4968: updates to inspect.is* function docs. ........ r85542 | georg.brandl | 2010-10-15 19:01:15 +0200 (Fr, 15 Okt 2010) | 1 line #7790: move table of struct_time members to the actual description of struct_time. ........ r85543 | georg.brandl | 2010-10-15 19:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #4785: document strict argument of JSONDecoder, plus add object_pairs_hook in the docstrings. ........ r85546 | georg.brandl | 2010-10-15 19:58:45 +0200 (Fr, 15 Okt 2010) | 1 line #5762: fix handling of empty namespace in minidom, which would result in AttributeError on toxml(). ........ r85547 | georg.brandl | 2010-10-15 20:00:35 +0200 (Fr, 15 Okt 2010) | 1 line #6098: Refrain from claiming DOM level 3 conformance in minidom. ........ r85548 | georg.brandl | 2010-10-15 21:46:19 +0200 (Fr, 15 Okt 2010) | 1 line #10072: assume a bit less knowledge of the FTP protocol in the ftplib docs. ........
2010-11-26 04:42:45 -04:00
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
"""
# cached encoder
if (not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
default is None and not kw):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
return cls(
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
separators=separators, default=default,
**kw).encode(obj)
_default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None)
def load(fp, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
Merged revisions 85530,85532-85534,85538-85543,85546-85548 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r85530 | georg.brandl | 2010-10-15 17:32:05 +0200 (Fr, 15 Okt 2010) | 1 line Refrain from using inline suites. ........ r85532 | georg.brandl | 2010-10-15 18:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #7771: reference to documentation of dictview methods and operations. ........ r85533 | georg.brandl | 2010-10-15 18:07:41 +0200 (Fr, 15 Okt 2010) | 1 line #9683: remove broken dead code dealing with nested arguments removed from Py3k, and update the docs and docstrings accordingly. ........ r85534 | georg.brandl | 2010-10-15 18:19:43 +0200 (Fr, 15 Okt 2010) | 1 line #9801: document how list and dict proxies created by Managers behave w.r.t. mutable items. ........ r85538 | georg.brandl | 2010-10-15 18:35:46 +0200 (Fr, 15 Okt 2010) | 1 line #7303: add documentation for useful pkgutil functions and classes. ........ r85539 | georg.brandl | 2010-10-15 18:42:14 +0200 (Fr, 15 Okt 2010) | 1 line Fix issue references. ........ r85540 | georg.brandl | 2010-10-15 18:42:37 +0200 (Fr, 15 Okt 2010) | 1 line #6798: fix wrong docs for the arguments to several trace events. ........ r85541 | georg.brandl | 2010-10-15 18:53:24 +0200 (Fr, 15 Okt 2010) | 1 line #4968: updates to inspect.is* function docs. ........ r85542 | georg.brandl | 2010-10-15 19:01:15 +0200 (Fr, 15 Okt 2010) | 1 line #7790: move table of struct_time members to the actual description of struct_time. ........ r85543 | georg.brandl | 2010-10-15 19:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #4785: document strict argument of JSONDecoder, plus add object_pairs_hook in the docstrings. ........ r85546 | georg.brandl | 2010-10-15 19:58:45 +0200 (Fr, 15 Okt 2010) | 1 line #5762: fix handling of empty namespace in minidom, which would result in AttributeError on toxml(). ........ r85547 | georg.brandl | 2010-10-15 20:00:35 +0200 (Fr, 15 Okt 2010) | 1 line #6098: Refrain from claiming DOM level 3 conformance in minidom. ........ r85548 | georg.brandl | 2010-10-15 21:46:19 +0200 (Fr, 15 Okt 2010) | 1 line #10072: assume a bit less knowledge of the FTP protocol in the ftplib docs. ........
2010-11-26 04:42:45 -04:00
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
Merged revisions 85530,85532-85534,85538-85543,85546-85548 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r85530 | georg.brandl | 2010-10-15 17:32:05 +0200 (Fr, 15 Okt 2010) | 1 line Refrain from using inline suites. ........ r85532 | georg.brandl | 2010-10-15 18:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #7771: reference to documentation of dictview methods and operations. ........ r85533 | georg.brandl | 2010-10-15 18:07:41 +0200 (Fr, 15 Okt 2010) | 1 line #9683: remove broken dead code dealing with nested arguments removed from Py3k, and update the docs and docstrings accordingly. ........ r85534 | georg.brandl | 2010-10-15 18:19:43 +0200 (Fr, 15 Okt 2010) | 1 line #9801: document how list and dict proxies created by Managers behave w.r.t. mutable items. ........ r85538 | georg.brandl | 2010-10-15 18:35:46 +0200 (Fr, 15 Okt 2010) | 1 line #7303: add documentation for useful pkgutil functions and classes. ........ r85539 | georg.brandl | 2010-10-15 18:42:14 +0200 (Fr, 15 Okt 2010) | 1 line Fix issue references. ........ r85540 | georg.brandl | 2010-10-15 18:42:37 +0200 (Fr, 15 Okt 2010) | 1 line #6798: fix wrong docs for the arguments to several trace events. ........ r85541 | georg.brandl | 2010-10-15 18:53:24 +0200 (Fr, 15 Okt 2010) | 1 line #4968: updates to inspect.is* function docs. ........ r85542 | georg.brandl | 2010-10-15 19:01:15 +0200 (Fr, 15 Okt 2010) | 1 line #7790: move table of struct_time members to the actual description of struct_time. ........ r85543 | georg.brandl | 2010-10-15 19:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #4785: document strict argument of JSONDecoder, plus add object_pairs_hook in the docstrings. ........ r85546 | georg.brandl | 2010-10-15 19:58:45 +0200 (Fr, 15 Okt 2010) | 1 line #5762: fix handling of empty namespace in minidom, which would result in AttributeError on toxml(). ........ r85547 | georg.brandl | 2010-10-15 20:00:35 +0200 (Fr, 15 Okt 2010) | 1 line #6098: Refrain from claiming DOM level 3 conformance in minidom. ........ r85548 | georg.brandl | 2010-10-15 21:46:19 +0200 (Fr, 15 Okt 2010) | 1 line #10072: assume a bit less knowledge of the FTP protocol in the ftplib docs. ........
2010-11-26 04:42:45 -04:00
kwarg; otherwise ``JSONDecoder`` is used.
"""
return loads(fp.read(),
cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``s`` (a ``str`` instance containing a JSON
document) to a Python object.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
Merged revisions 85530,85532-85534,85538-85543,85546-85548 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r85530 | georg.brandl | 2010-10-15 17:32:05 +0200 (Fr, 15 Okt 2010) | 1 line Refrain from using inline suites. ........ r85532 | georg.brandl | 2010-10-15 18:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #7771: reference to documentation of dictview methods and operations. ........ r85533 | georg.brandl | 2010-10-15 18:07:41 +0200 (Fr, 15 Okt 2010) | 1 line #9683: remove broken dead code dealing with nested arguments removed from Py3k, and update the docs and docstrings accordingly. ........ r85534 | georg.brandl | 2010-10-15 18:19:43 +0200 (Fr, 15 Okt 2010) | 1 line #9801: document how list and dict proxies created by Managers behave w.r.t. mutable items. ........ r85538 | georg.brandl | 2010-10-15 18:35:46 +0200 (Fr, 15 Okt 2010) | 1 line #7303: add documentation for useful pkgutil functions and classes. ........ r85539 | georg.brandl | 2010-10-15 18:42:14 +0200 (Fr, 15 Okt 2010) | 1 line Fix issue references. ........ r85540 | georg.brandl | 2010-10-15 18:42:37 +0200 (Fr, 15 Okt 2010) | 1 line #6798: fix wrong docs for the arguments to several trace events. ........ r85541 | georg.brandl | 2010-10-15 18:53:24 +0200 (Fr, 15 Okt 2010) | 1 line #4968: updates to inspect.is* function docs. ........ r85542 | georg.brandl | 2010-10-15 19:01:15 +0200 (Fr, 15 Okt 2010) | 1 line #7790: move table of struct_time members to the actual description of struct_time. ........ r85543 | georg.brandl | 2010-10-15 19:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #4785: document strict argument of JSONDecoder, plus add object_pairs_hook in the docstrings. ........ r85546 | georg.brandl | 2010-10-15 19:58:45 +0200 (Fr, 15 Okt 2010) | 1 line #5762: fix handling of empty namespace in minidom, which would result in AttributeError on toxml(). ........ r85547 | georg.brandl | 2010-10-15 20:00:35 +0200 (Fr, 15 Okt 2010) | 1 line #6098: Refrain from claiming DOM level 3 conformance in minidom. ........ r85548 | georg.brandl | 2010-10-15 21:46:19 +0200 (Fr, 15 Okt 2010) | 1 line #10072: assume a bit less knowledge of the FTP protocol in the ftplib docs. ........
2010-11-26 04:42:45 -04:00
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
Merged revisions 85530,85532-85534,85538-85543,85546-85548 via svnmerge from svn+ssh://svn.python.org/python/branches/py3k ........ r85530 | georg.brandl | 2010-10-15 17:32:05 +0200 (Fr, 15 Okt 2010) | 1 line Refrain from using inline suites. ........ r85532 | georg.brandl | 2010-10-15 18:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #7771: reference to documentation of dictview methods and operations. ........ r85533 | georg.brandl | 2010-10-15 18:07:41 +0200 (Fr, 15 Okt 2010) | 1 line #9683: remove broken dead code dealing with nested arguments removed from Py3k, and update the docs and docstrings accordingly. ........ r85534 | georg.brandl | 2010-10-15 18:19:43 +0200 (Fr, 15 Okt 2010) | 1 line #9801: document how list and dict proxies created by Managers behave w.r.t. mutable items. ........ r85538 | georg.brandl | 2010-10-15 18:35:46 +0200 (Fr, 15 Okt 2010) | 1 line #7303: add documentation for useful pkgutil functions and classes. ........ r85539 | georg.brandl | 2010-10-15 18:42:14 +0200 (Fr, 15 Okt 2010) | 1 line Fix issue references. ........ r85540 | georg.brandl | 2010-10-15 18:42:37 +0200 (Fr, 15 Okt 2010) | 1 line #6798: fix wrong docs for the arguments to several trace events. ........ r85541 | georg.brandl | 2010-10-15 18:53:24 +0200 (Fr, 15 Okt 2010) | 1 line #4968: updates to inspect.is* function docs. ........ r85542 | georg.brandl | 2010-10-15 19:01:15 +0200 (Fr, 15 Okt 2010) | 1 line #7790: move table of struct_time members to the actual description of struct_time. ........ r85543 | georg.brandl | 2010-10-15 19:03:02 +0200 (Fr, 15 Okt 2010) | 1 line #4785: document strict argument of JSONDecoder, plus add object_pairs_hook in the docstrings. ........ r85546 | georg.brandl | 2010-10-15 19:58:45 +0200 (Fr, 15 Okt 2010) | 1 line #5762: fix handling of empty namespace in minidom, which would result in AttributeError on toxml(). ........ r85547 | georg.brandl | 2010-10-15 20:00:35 +0200 (Fr, 15 Okt 2010) | 1 line #6098: Refrain from claiming DOM level 3 conformance in minidom. ........ r85548 | georg.brandl | 2010-10-15 21:46:19 +0200 (Fr, 15 Okt 2010) | 1 line #10072: assume a bit less knowledge of the FTP protocol in the ftplib docs. ........
2010-11-26 04:42:45 -04:00
kwarg; otherwise ``JSONDecoder`` is used.
The ``encoding`` argument is ignored and deprecated.
"""
if (cls is None and object_hook is None and
parse_int is None and parse_float is None and
parse_constant is None and object_pairs_hook is None and not kw):
return _default_decoder.decode(s)
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
if object_pairs_hook is not None:
kw['object_pairs_hook'] = object_pairs_hook
if parse_float is not None:
kw['parse_float'] = parse_float
if parse_int is not None:
kw['parse_int'] = parse_int
if parse_constant is not None:
kw['parse_constant'] = parse_constant
return cls(**kw).decode(s)