+++ /dev/null
-r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of\r
-JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data\r
-interchange format.\r
-\r
-:mod:`json` exposes an API familiar to users of the standard library\r
-:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained\r
-version of the :mod:`json` library contained in Python 2.6, but maintains\r
-compatibility with Python 2.4 and Python 2.5 and (currently) has\r
-significant performance advantages, even without using the optional C\r
-extension for speedups.\r
-\r
-Encoding basic Python object hierarchies::\r
-\r
- >>> import json\r
- >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])\r
- '["foo", {"bar": ["baz", null, 1.0, 2]}]'\r
- >>> print json.dumps("\"foo\bar")\r
- "\"foo\bar"\r
- >>> print json.dumps(u'\u1234')\r
- "\u1234"\r
- >>> print json.dumps('\\')\r
- "\\"\r
- >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)\r
- {"a": 0, "b": 0, "c": 0}\r
- >>> from StringIO import StringIO\r
- >>> io = StringIO()\r
- >>> json.dump(['streaming API'], io)\r
- >>> io.getvalue()\r
- '["streaming API"]'\r
-\r
-Compact encoding::\r
-\r
- >>> import json\r
- >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))\r
- '[1,2,3,{"4":5,"6":7}]'\r
-\r
-Pretty printing::\r
-\r
- >>> import json\r
- >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)\r
- >>> print '\n'.join([l.rstrip() for l in s.splitlines()])\r
- {\r
- "4": 5,\r
- "6": 7\r
- }\r
-\r
-Decoding JSON::\r
-\r
- >>> import json\r
- >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]\r
- >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj\r
- True\r
- >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'\r
- True\r
- >>> from StringIO import StringIO\r
- >>> io = StringIO('["streaming API"]')\r
- >>> json.load(io)[0] == 'streaming API'\r
- True\r
-\r
-Specializing JSON object decoding::\r
-\r
- >>> import json\r
- >>> def as_complex(dct):\r
- ... if '__complex__' in dct:\r
- ... return complex(dct['real'], dct['imag'])\r
- ... return dct\r
- ...\r
- >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',\r
- ... object_hook=as_complex)\r
- (1+2j)\r
- >>> from decimal import Decimal\r
- >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')\r
- True\r
-\r
-Specializing JSON object encoding::\r
-\r
- >>> import json\r
- >>> def encode_complex(obj):\r
- ... if isinstance(obj, complex):\r
- ... return [obj.real, obj.imag]\r
- ... raise TypeError(repr(o) + " is not JSON serializable")\r
- ...\r
- >>> json.dumps(2 + 1j, default=encode_complex)\r
- '[2.0, 1.0]'\r
- >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)\r
- '[2.0, 1.0]'\r
- >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))\r
- '[2.0, 1.0]'\r
-\r
-\r
-Using json.tool from the shell to validate and pretty-print::\r
-\r
- $ echo '{"json":"obj"}' | python -m json.tool\r
- {\r
- "json": "obj"\r
- }\r
- $ echo '{ 1.2:3.4}' | python -m json.tool\r
- Expecting property name: line 1 column 2 (char 2)\r
-"""\r
-__version__ = '2.0.9'\r
-__all__ = [\r
- 'dump', 'dumps', 'load', 'loads',\r
- 'JSONDecoder', 'JSONEncoder',\r
-]\r
-\r
-__author__ = 'Bob Ippolito <bob@redivi.com>'\r
-\r
-from .decoder import JSONDecoder\r
-from .encoder import JSONEncoder\r
-\r
-_default_encoder = JSONEncoder(\r
- skipkeys=False,\r
- ensure_ascii=True,\r
- check_circular=True,\r
- allow_nan=True,\r
- indent=None,\r
- separators=None,\r
- encoding='utf-8',\r
- default=None,\r
-)\r
-\r
-def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,\r
- allow_nan=True, cls=None, indent=None, separators=None,\r
- encoding='utf-8', default=None, **kw):\r
- """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a\r
- ``.write()``-supporting file-like object).\r
-\r
- If ``skipkeys`` is true then ``dict`` keys that are not basic types\r
- (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\r
- will be skipped instead of raising a ``TypeError``.\r
-\r
- If ``ensure_ascii`` is false, then the some chunks written to ``fp``\r
- may be ``unicode`` instances, subject to normal Python ``str`` to\r
- ``unicode`` coercion rules. Unless ``fp.write()`` explicitly\r
- understands ``unicode`` (as in ``codecs.getwriter()``) this is likely\r
- to cause an error.\r
-\r
- If ``check_circular`` is false, then the circular reference check\r
- for container types will be skipped and a circular reference will\r
- result in an ``OverflowError`` (or worse).\r
-\r
- If ``allow_nan`` is false, then it will be a ``ValueError`` to\r
- serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)\r
- in strict compliance of the JSON specification, instead of using the\r
- JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\r
-\r
- If ``indent`` is a non-negative integer, then JSON array elements and\r
- object members will be pretty-printed with that indent level. An indent\r
- level of 0 will only insert newlines. ``None`` is the most compact\r
- representation.\r
-\r
- If ``separators`` is an ``(item_separator, dict_separator)`` tuple\r
- then it will be used instead of the default ``(', ', ': ')`` separators.\r
- ``(',', ':')`` is the most compact JSON representation.\r
-\r
- ``encoding`` is the character encoding for str instances, default is UTF-8.\r
-\r
- ``default(obj)`` is a function that should return a serializable version\r
- of obj or raise TypeError. The default simply raises TypeError.\r
-\r
- To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\r
- ``.default()`` method to serialize additional types), specify it with\r
- the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.\r
-\r
- """\r
- # cached encoder\r
- if (not skipkeys and ensure_ascii and\r
- check_circular and allow_nan and\r
- cls is None and indent is None and separators is None and\r
- encoding == 'utf-8' and default is None and not kw):\r
- iterable = _default_encoder.iterencode(obj)\r
- else:\r
- if cls is None:\r
- cls = JSONEncoder\r
- iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,\r
- check_circular=check_circular, allow_nan=allow_nan, indent=indent,\r
- separators=separators, encoding=encoding,\r
- default=default, **kw).iterencode(obj)\r
- # could accelerate with writelines in some versions of Python, at\r
- # a debuggability cost\r
- for chunk in iterable:\r
- fp.write(chunk)\r
-\r
-\r
-def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,\r
- allow_nan=True, cls=None, indent=None, separators=None,\r
- encoding='utf-8', default=None, **kw):\r
- """Serialize ``obj`` to a JSON formatted ``str``.\r
-\r
- If ``skipkeys`` is false then ``dict`` keys that are not basic types\r
- (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)\r
- will be skipped instead of raising a ``TypeError``.\r
-\r
- If ``ensure_ascii`` is false, then the return value will be a\r
- ``unicode`` instance subject to normal Python ``str`` to ``unicode``\r
- coercion rules instead of being escaped to an ASCII ``str``.\r
-\r
- If ``check_circular`` is false, then the circular reference check\r
- for container types will be skipped and a circular reference will\r
- result in an ``OverflowError`` (or worse).\r
-\r
- If ``allow_nan`` is false, then it will be a ``ValueError`` to\r
- serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in\r
- strict compliance of the JSON specification, instead of using the\r
- JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).\r
-\r
- If ``indent`` is a non-negative integer, then JSON array elements and\r
- object members will be pretty-printed with that indent level. An indent\r
- level of 0 will only insert newlines. ``None`` is the most compact\r
- representation.\r
-\r
- If ``separators`` is an ``(item_separator, dict_separator)`` tuple\r
- then it will be used instead of the default ``(', ', ': ')`` separators.\r
- ``(',', ':')`` is the most compact JSON representation.\r
-\r
- ``encoding`` is the character encoding for str instances, default is UTF-8.\r
-\r
- ``default(obj)`` is a function that should return a serializable version\r
- of obj or raise TypeError. The default simply raises TypeError.\r
-\r
- To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the\r
- ``.default()`` method to serialize additional types), specify it with\r
- the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.\r
-\r
- """\r
- # cached encoder\r
- if (not skipkeys and ensure_ascii and\r
- check_circular and allow_nan and\r
- cls is None and indent is None and separators is None and\r
- encoding == 'utf-8' and default is None and not kw):\r
- return _default_encoder.encode(obj)\r
- if cls is None:\r
- cls = JSONEncoder\r
- return cls(\r
- skipkeys=skipkeys, ensure_ascii=ensure_ascii,\r
- check_circular=check_circular, allow_nan=allow_nan, indent=indent,\r
- separators=separators, encoding=encoding, default=default,\r
- **kw).encode(obj)\r
-\r
-\r
-_default_decoder = JSONDecoder(encoding=None, object_hook=None,\r
- object_pairs_hook=None)\r
-\r
-\r
-def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,\r
- parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):\r
- """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing\r
- a JSON document) to a Python object.\r
-\r
- If the contents of ``fp`` is encoded with an ASCII based encoding other\r
- than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must\r
- be specified. Encodings that are not ASCII based (such as UCS-2) are\r
- not allowed, and should be wrapped with\r
- ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``\r
- object and passed to ``loads()``\r
-\r
- ``object_hook`` is an optional function that will be called with the\r
- result of any object literal decode (a ``dict``). The return value of\r
- ``object_hook`` will be used instead of the ``dict``. This feature\r
- can be used to implement custom decoders (e.g. JSON-RPC class hinting).\r
-\r
- ``object_pairs_hook`` is an optional function that will be called with the\r
- result of any object literal decoded with an ordered list of pairs. The\r
- return value of ``object_pairs_hook`` will be used instead of the ``dict``.\r
- This feature can be used to implement custom decoders that rely on the\r
- order that the key and value pairs are decoded (for example,\r
- collections.OrderedDict will remember the order of insertion). If\r
- ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.\r
-\r
- To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``\r
- kwarg; otherwise ``JSONDecoder`` is used.\r
-\r
- """\r
- return loads(fp.read(),\r
- encoding=encoding, cls=cls, object_hook=object_hook,\r
- parse_float=parse_float, parse_int=parse_int,\r
- parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,\r
- **kw)\r
-\r
-\r
-def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,\r
- parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):\r
- """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON\r
- document) to a Python object.\r
-\r
- If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding\r
- other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name\r
- must be specified. Encodings that are not ASCII based (such as UCS-2)\r
- are not allowed and should be decoded to ``unicode`` first.\r
-\r
- ``object_hook`` is an optional function that will be called with the\r
- result of any object literal decode (a ``dict``). The return value of\r
- ``object_hook`` will be used instead of the ``dict``. This feature\r
- can be used to implement custom decoders (e.g. JSON-RPC class hinting).\r
-\r
- ``object_pairs_hook`` is an optional function that will be called with the\r
- result of any object literal decoded with an ordered list of pairs. The\r
- return value of ``object_pairs_hook`` will be used instead of the ``dict``.\r
- This feature can be used to implement custom decoders that rely on the\r
- order that the key and value pairs are decoded (for example,\r
- collections.OrderedDict will remember the order of insertion). If\r
- ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.\r
-\r
- ``parse_float``, if specified, will be called with the string\r
- of every JSON float to be decoded. By default this is equivalent to\r
- float(num_str). This can be used to use another datatype or parser\r
- for JSON floats (e.g. decimal.Decimal).\r
-\r
- ``parse_int``, if specified, will be called with the string\r
- of every JSON int to be decoded. By default this is equivalent to\r
- int(num_str). This can be used to use another datatype or parser\r
- for JSON integers (e.g. float).\r
-\r
- ``parse_constant``, if specified, will be called with one of the\r
- following strings: -Infinity, Infinity, NaN, null, true, false.\r
- This can be used to raise an exception if invalid JSON numbers\r
- are encountered.\r
-\r
- To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``\r
- kwarg; otherwise ``JSONDecoder`` is used.\r
-\r
- """\r
- if (cls is None and encoding is None and object_hook is None and\r
- parse_int is None and parse_float is None and\r
- parse_constant is None and object_pairs_hook is None and not kw):\r
- return _default_decoder.decode(s)\r
- if cls is None:\r
- cls = JSONDecoder\r
- if object_hook is not None:\r
- kw['object_hook'] = object_hook\r
- if object_pairs_hook is not None:\r
- kw['object_pairs_hook'] = object_pairs_hook\r
- if parse_float is not None:\r
- kw['parse_float'] = parse_float\r
- if parse_int is not None:\r
- kw['parse_int'] = parse_int\r
- if parse_constant is not None:\r
- kw['parse_constant'] = parse_constant\r
- return cls(encoding=encoding, **kw).decode(s)\r