0001r"""
0002A simple, fast, extensible JSON encoder and decoder
0003
0004JSON (JavaScript Object Notation) <http://json.org> is a subset of
0005JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
0006interchange format.
0007
0008simplejson exposes an API familiar to uses of the standard library
0009marshal and pickle modules.
0010
0011Encoding basic Python object hierarchies::
0012
0013 >>> import simplejson
0014 >>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
0015 '["foo", {"bar": ["baz", null, 1.0, 2]}]'
0016 >>> print simplejson.dumps("\"foo\bar")
0017 "\"foo\bar"
0018 >>> print simplejson.dumps(u'\u1234')
0019 "\u1234"
0020 >>> print simplejson.dumps('\\')
0021 "\\"
0022 >>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
0023 {"a": 0, "b": 0, "c": 0}
0024 >>> from StringIO import StringIO
0025 >>> io = StringIO()
0026 >>> simplejson.dump(['streaming API'], io)
0027 >>> io.getvalue()
0028 '["streaming API"]'
0029
0030Decoding JSON::
0031
0032 >>> import simplejson
0033 >>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
0034 [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
0035 >>> simplejson.loads('"\\"foo\\bar"')
0036 u'"foo\x08ar'
0037 >>> from StringIO import StringIO
0038 >>> io = StringIO('["streaming API"]')
0039 >>> simplejson.load(io)
0040 [u'streaming API']
0041
0042Specializing JSON object decoding::
0043
0044 >>> import simplejson
0045 >>> def as_complex(dct):
0046 ... if '__complex__' in dct:
0047 ... return complex(dct['real'], dct['imag'])
0048 ... return dct
0049 ...
0050 >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',
0051 ... object_hook=as_complex)
0052 (1+2j)
0053
0054Extending JSONEncoder::
0055
0056 >>> import simplejson
0057 >>> class ComplexEncoder(simplejson.JSONEncoder):
0058 ... def default(self, obj):
0059 ... if isinstance(obj, complex):
0060 ... return [obj.real, obj.imag]
0061 ... return simplejson.JSONEncoder.default(self, obj)
0062 ...
0063 >>> dumps(2 + 1j, cls=ComplexEncoder)
0064 '[2.0, 1.0]'
0065 >>> ComplexEncoder().encode(2 + 1j)
0066 '[2.0, 1.0]'
0067 >>> list(ComplexEncoder().iterencode(2 + 1j))
0068 ['[', '2.0', ', ', '1.0', ']']
0069
0070
0071Note that the JSON produced by this module is a subset of YAML,
0072so it may be used as a serializer for that as well.
0073"""
0074__version__ = '1.3'
0075__all__ = [
0076 'dump', 'dumps', 'load', 'loads',
0077 'JSONDecoder', 'JSONEncoder',
0078]
0079
0080from decoder import JSONDecoder
0081from encoder import JSONEncoder
0082
0083def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
0084 allow_nan=True, cls=None, **kw):
0085 """
0086 Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
0087 ``.write()``-supporting file-like object).
0088
0089 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
0090 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
0091 will be skipped instead of raising a ``TypeError``.
0092
0093 If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
0094 may be ``unicode`` instances, subject to normal Python ``str`` to
0095 ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
0096 understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
0097 to cause an error.
0098
0099 If ``check_circular`` is ``False``, then the circular reference check
0100 for container types will be skipped and a circular reference will
0101 result in an ``OverflowError`` (or worse).
0102
0103 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
0104 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
0105 in strict compliance of the JSON specification, instead of using the
0106 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
0107
0108 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
0109 ``.default()`` method to serialize additional types), specify it with
0110 the ``cls`` kwarg.
0111 """
0112 if cls is None:
0113 cls = JSONEncoder
0114 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
0115 check_circular=check_circular, allow_nan=allow_nan,
0116 **kw).iterencode(obj)
0117
0118
0119 for chunk in iterable:
0120 fp.write(chunk)
0121
0122def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
0123 allow_nan=True, cls=None, **kw):
0124 """
0125 Serialize ``obj`` to a JSON formatted ``str``.
0126
0127 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
0128 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
0129 will be skipped instead of raising a ``TypeError``.
0130
0131 If ``ensure_ascii`` is ``False``, then the return value will be a
0132 ``unicode`` instance subject to normal Python ``str`` to ``unicode``
0133 coercion rules instead of being escaped to an ASCII ``str``.
0134
0135 If ``check_circular`` is ``False``, then the circular reference check
0136 for container types will be skipped and a circular reference will
0137 result in an ``OverflowError`` (or worse).
0138
0139 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
0140 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
0141 strict compliance of the JSON specification, instead of using the
0142 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
0143
0144 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
0145 ``.default()`` method to serialize additional types), specify it with
0146 the ``cls`` kwarg.
0147 """
0148 if cls is None:
0149 cls = JSONEncoder
0150 return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
0151 check_circular=check_circular, allow_nan=allow_nan, **kw).encode(obj)
0152
0153def load(fp, encoding=None, cls=None, object_hook=None, **kw):
0154 """
0155 Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
0156 a JSON document) to a Python object.
0157
0158 If the contents of ``fp`` is encoded with an ASCII based encoding other
0159 than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
0160 be specified. Encodings that are not ASCII based (such as UCS-2) are
0161 not allowed, and should be wrapped with
0162 ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
0163 object and passed to ``loads()``
0164
0165 ``object_hook`` is an optional function that will be called with the
0166 result of any object literal decode (a ``dict``). The return value of
0167 ``object_hook`` will be used instead of the ``dict``. This feature
0168 can be used to implement custom decoders (e.g. JSON-RPC class hinting).
0169
0170 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
0171 kwarg.
0172 """
0173 if cls is None:
0174 cls = JSONDecoder
0175 if object_hook is not None:
0176 kw['object_hook'] = object_hook
0177 return cls(encoding=encoding, **kw).decode(fp.read())
0178
0179def loads(s, encoding=None, cls=None, object_hook=None, **kw):
0180 """
0181 Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
0182 document) to a Python object.
0183
0184 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
0185 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
0186 must be specified. Encodings that are not ASCII based (such as UCS-2)
0187 are not allowed and should be decoded to ``unicode`` first.
0188
0189 ``object_hook`` is an optional function that will be called with the
0190 result of any object literal decode (a ``dict``). The return value of
0191 ``object_hook`` will be used instead of the ``dict``. This feature
0192 can be used to implement custom decoders (e.g. JSON-RPC class hinting).
0193
0194 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
0195 kwarg.
0196 """
0197 if cls is None:
0198 cls = JSONDecoder
0199 if object_hook is not None:
0200 kw['object_hook'] = object_hook
0201 return cls(encoding=encoding, **kw).decode(s)
0202
0203def read(s):
0204 """
0205 json-py API compatibility hook. Use loads(s) instead.
0206 """
0207 import warnings
0208 warnings.warn("simplejson.loads(s) should be used instead of read(s)",
0209 DeprecationWarning)
0210 return loads(s)
0211
0212def write(obj):
0213 """
0214 json-py API compatibility hook. Use dumps(s) instead.
0215 """
0216 import warnings
0217 warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
0218 DeprecationWarning)
0219 return dumps(obj)