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 >>> from StringIO import StringIO
0023 >>> io = StringIO()
0024 >>> simplejson.dump(['streaming API'], io)
0025 >>> io.getvalue()
0026 '["streaming API"]'
0027
0028Decoding JSON::
0029
0030 >>> import simplejson
0031 >>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
0032 [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
0033 >>> simplejson.loads('"\\"foo\\bar"')
0034 u'"foo\x08ar'
0035 >>> from StringIO import StringIO
0036 >>> io = StringIO('["streaming API"]')
0037 >>> simplejson.load(io)
0038 [u'streaming API']
0039
0040Extending JSONEncoder::
0041
0042 >>> import simplejson
0043 >>> class ComplexEncoder(simplejson.JSONEncoder):
0044 ... def default(self, obj):
0045 ... if isinstance(obj, complex):
0046 ... return [obj.real, obj.imag]
0047 ... return simplejson.JSONEncoder.default(self, obj)
0048 ...
0049 >>> dumps(2 + 1j, cls=ComplexEncoder)
0050 '[2.0, 1.0]'
0051 >>> ComplexEncoder().encode(2 + 1j)
0052 '[2.0, 1.0]'
0053 >>> list(ComplexEncoder().iterencode(2 + 1j))
0054 ['[', '2.0', ', ', '1.0', ']']
0055
0056
0057Note that the JSON produced by this module is a subset of YAML,
0058so it may be used as a serializer for that as well.
0059"""
0060__version__ = '1.1'
0061__all__ = [
0062 'dump', 'dumps', 'load', 'loads',
0063 'JSONDecoder', 'JSONEncoder',
0064]
0065
0066from decoder import JSONDecoder
0067from encoder import JSONEncoder
0068
0069def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
0070 allow_nan=True, cls=None, **kw):
0071 """
0072 Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
0073 ``.write()``-supporting file-like object).
0074
0075 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
0076 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
0077 will be skipped instead of raising a ``TypeError``.
0078
0079 If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
0080 may be ``unicode`` instances, subject to normal Python ``str`` to
0081 ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
0082 understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
0083 to cause an error.
0084
0085 If ``check_circular`` is ``False``, then the circular reference check
0086 for container types will be skipped and a circular reference will
0087 result in an ``OverflowError`` (or worse).
0088
0089 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
0090 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
0091 in strict compliance of the JSON specification, instead of using the
0092 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
0093
0094 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
0095 ``.default()`` method to serialize additional types), specify it with
0096 the ``cls`` kwarg.
0097 """
0098 if cls is None:
0099 cls = JSONEncoder
0100 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
0101 check_circular=check_circular, allow_nan=allow_nan,
0102 **kw).iterencode(obj)
0103
0104
0105 for chunk in iterable:
0106 fp.write(chunk)
0107
0108def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
0109 allow_nan=True, cls=None, **kw):
0110 """
0111 Serialize ``obj`` to a JSON formatted ``str``.
0112
0113 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
0114 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
0115 will be skipped instead of raising a ``TypeError``.
0116
0117 If ``ensure_ascii`` is ``False``, then the return value will be a
0118 ``unicode`` instance subject to normal Python ``str`` to ``unicode``
0119 coercion rules instead of being escaped to an ASCII ``str``.
0120
0121 If ``check_circular`` is ``False``, then the circular reference check
0122 for container types will be skipped and a circular reference will
0123 result in an ``OverflowError`` (or worse).
0124
0125 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
0126 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
0127 strict compliance of the JSON specification, instead of using the
0128 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
0129
0130 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
0131 ``.default()`` method to serialize additional types), specify it with
0132 the ``cls`` kwarg.
0133 """
0134 if cls is None:
0135 cls = JSONEncoder
0136 return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
0137 check_circular=check_circular, allow_nan=allow_nan, **kw).encode(obj)
0138
0139def load(fp, encoding=None, cls=None, **kw):
0140 """
0141 Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
0142 a JSON document) to a Python object.
0143
0144 If the contents of ``fp`` is encoded with an ASCII based encoding other
0145 than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
0146 be specified. Encodings that are not ASCII based (such as UCS-2) are
0147 not allowed, and should be wrapped with
0148 ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
0149 object and passed to ``loads()``
0150
0151 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
0152 kwarg.
0153 """
0154 if cls is None:
0155 cls = JSONDecoder
0156 return cls(encoding=encoding, **kw).decode(fp.read())
0157
0158def loads(s, encoding=None, cls=None, **kw):
0159 """
0160 Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
0161 document) to a Python object.
0162
0163 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
0164 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
0165 must be specified. Encodings that are not ASCII based (such as UCS-2)
0166 are not allowed and should be decoded to ``unicode`` first.
0167
0168 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
0169 kwarg.
0170 """
0171 if cls is None:
0172 cls = JSONDecoder
0173 return cls(encoding=encoding, **kw).decode(s)
0174
0175def read(s):
0176 """
0177 json-py API compatibility hook. Use loads(s) instead.
0178 """
0179 import warnings
0180 warnings.warn("simplejson.loads(s) should be used instead of read(s)",
0181 DeprecationWarning)
0182 return loads(s)
0183
0184def write(obj):
0185 """
0186 json-py API compatibility hook. Use dumps(s) instead.
0187 """
0188 import warnings
0189 warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
0190 DeprecationWarning)
0191 return dumps(obj)