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
0030Compact encoding::
0031
0032 >>> import simplejson
0033 >>> simplejson.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
0034 '[1,2,3,{"4":5,"6":7}]'
0035
0036Pretty printing::
0037
0038 >>> import simplejson
0039 >>> print simplejson.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
0040 {
0041 "4": 5,
0042 "6": 7
0043 }
0044
0045Decoding JSON::
0046
0047 >>> import simplejson
0048 >>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
0049 [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
0050 >>> simplejson.loads('"\\"foo\\bar"')
0051 u'"foo\x08ar'
0052 >>> from StringIO import StringIO
0053 >>> io = StringIO('["streaming API"]')
0054 >>> simplejson.load(io)
0055 [u'streaming API']
0056
0057Specializing JSON object decoding::
0058
0059 >>> import simplejson
0060 >>> def as_complex(dct):
0061 ... if '__complex__' in dct:
0062 ... return complex(dct['real'], dct['imag'])
0063 ... return dct
0064 ...
0065 >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',
0066 ... object_hook=as_complex)
0067 (1+2j)
0068
0069Extending JSONEncoder::
0070
0071 >>> import simplejson
0072 >>> class ComplexEncoder(simplejson.JSONEncoder):
0073 ... def default(self, obj):
0074 ... if isinstance(obj, complex):
0075 ... return [obj.real, obj.imag]
0076 ... return simplejson.JSONEncoder.default(self, obj)
0077 ...
0078 >>> dumps(2 + 1j, cls=ComplexEncoder)
0079 '[2.0, 1.0]'
0080 >>> ComplexEncoder().encode(2 + 1j)
0081 '[2.0, 1.0]'
0082 >>> list(ComplexEncoder().iterencode(2 + 1j))
0083 ['[', '2.0', ', ', '1.0', ']']
0084
0085
0086Note that the JSON produced by this module's default settings
0087is a subset of YAML, so it may be used as a serializer for that as well.
0088"""
0089__version__ = '1.5'
0090__all__ = [
0091 'dump', 'dumps', 'load', 'loads',
0092 'JSONDecoder', 'JSONEncoder',
0093]
0094
0095from decoder import JSONDecoder
0096from encoder import JSONEncoder
0097
0098def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
0099 allow_nan=True, cls=None, indent=None, **kw):
0100 """
0101 Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
0102 ``.write()``-supporting file-like object).
0103
0104 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
0105 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
0106 will be skipped instead of raising a ``TypeError``.
0107
0108 If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
0109 may be ``unicode`` instances, subject to normal Python ``str`` to
0110 ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
0111 understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
0112 to cause an error.
0113
0114 If ``check_circular`` is ``False``, then the circular reference check
0115 for container types will be skipped and a circular reference will
0116 result in an ``OverflowError`` (or worse).
0117
0118 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
0119 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
0120 in strict compliance of the JSON specification, instead of using the
0121 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
0122
0123 If ``indent`` is a non-negative integer, then JSON array elements and object
0124 members will be pretty-printed with that indent level. An indent level
0125 of 0 will only insert newlines. ``None`` is the most compact representation.
0126
0127 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
0128 ``.default()`` method to serialize additional types), specify it with
0129 the ``cls`` kwarg.
0130 """
0131 if cls is None:
0132 cls = JSONEncoder
0133 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
0134 check_circular=check_circular, allow_nan=allow_nan, indent=indent,
0135 **kw).iterencode(obj)
0136
0137
0138 for chunk in iterable:
0139 fp.write(chunk)
0140
0141def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
0142 allow_nan=True, cls=None, indent=None, separators=None, **kw):
0143 """
0144 Serialize ``obj`` to a JSON formatted ``str``.
0145
0146 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
0147 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
0148 will be skipped instead of raising a ``TypeError``.
0149
0150 If ``ensure_ascii`` is ``False``, then the return value will be a
0151 ``unicode`` instance subject to normal Python ``str`` to ``unicode``
0152 coercion rules instead of being escaped to an ASCII ``str``.
0153
0154 If ``check_circular`` is ``False``, then the circular reference check
0155 for container types will be skipped and a circular reference will
0156 result in an ``OverflowError`` (or worse).
0157
0158 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
0159 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
0160 strict compliance of the JSON specification, instead of using the
0161 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
0162
0163 If ``indent`` is a non-negative integer, then JSON array elements and
0164 object members will be pretty-printed with that indent level. An indent
0165 level of 0 will only insert newlines. ``None`` is the most compact
0166 representation.
0167
0168 If ``separators`` is an ``(item_separator, dict_separator)`` tuple
0169 then it will be used instead of the default ``(', ', ': ')`` separators.
0170 ``(',', ':')`` is the most compact JSON representation.
0171
0172 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
0173 ``.default()`` method to serialize additional types), specify it with
0174 the ``cls`` kwarg.
0175 """
0176 if cls is None:
0177 cls = JSONEncoder
0178 return cls(
0179 skipkeys=skipkeys, ensure_ascii=ensure_ascii,
0180 check_circular=check_circular, allow_nan=allow_nan, indent=indent,
0181 separators=separators,
0182 **kw).encode(obj)
0183
0184def load(fp, encoding=None, cls=None, object_hook=None, **kw):
0185 """
0186 Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
0187 a JSON document) to a Python object.
0188
0189 If the contents of ``fp`` is encoded with an ASCII based encoding other
0190 than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
0191 be specified. Encodings that are not ASCII based (such as UCS-2) are
0192 not allowed, and should be wrapped with
0193 ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
0194 object and passed to ``loads()``
0195
0196 ``object_hook`` is an optional function that will be called with the
0197 result of any object literal decode (a ``dict``). The return value of
0198 ``object_hook`` will be used instead of the ``dict``. This feature
0199 can be used to implement custom decoders (e.g. JSON-RPC class hinting).
0200
0201 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
0202 kwarg.
0203 """
0204 if cls is None:
0205 cls = JSONDecoder
0206 if object_hook is not None:
0207 kw['object_hook'] = object_hook
0208 return cls(encoding=encoding, **kw).decode(fp.read())
0209
0210def loads(s, encoding=None, cls=None, object_hook=None, **kw):
0211 """
0212 Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
0213 document) to a Python object.
0214
0215 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
0216 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
0217 must be specified. Encodings that are not ASCII based (such as UCS-2)
0218 are not allowed and should be decoded to ``unicode`` first.
0219
0220 ``object_hook`` is an optional function that will be called with the
0221 result of any object literal decode (a ``dict``). The return value of
0222 ``object_hook`` will be used instead of the ``dict``. This feature
0223 can be used to implement custom decoders (e.g. JSON-RPC class hinting).
0224
0225 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
0226 kwarg.
0227 """
0228 if cls is None:
0229 cls = JSONDecoder
0230 if object_hook is not None:
0231 kw['object_hook'] = object_hook
0232 return cls(encoding=encoding, **kw).decode(s)
0233
0234def read(s):
0235 """
0236 json-py API compatibility hook. Use loads(s) instead.
0237 """
0238 import warnings
0239 warnings.warn("simplejson.loads(s) should be used instead of read(s)",
0240 DeprecationWarning)
0241 return loads(s)
0242
0243def write(obj):
0244 """
0245 json-py API compatibility hook. Use dumps(s) instead.
0246 """
0247 import warnings
0248 warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
0249 DeprecationWarning)
0250 return dumps(obj)