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.7.5'
0090__all__ = [
0091 'dump', 'dumps', 'load', 'loads',
0092 'JSONDecoder', 'JSONEncoder',
0093]
0094
0095from decoder import JSONDecoder
0096from encoder import JSONEncoder
0097
0098_default_encoder = JSONEncoder(
0099 skipkeys=False,
0100 ensure_ascii=True,
0101 check_circular=True,
0102 allow_nan=True,
0103 indent=None,
0104 separators=None,
0105 encoding='utf-8'
0106)
0107
0108def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
0109 allow_nan=True, cls=None, indent=None, separators=None,
0110 encoding='utf-8', **kw):
0111 """
0112 Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
0113 ``.write()``-supporting file-like object).
0114
0115 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
0116 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
0117 will be skipped instead of raising a ``TypeError``.
0118
0119 If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
0120 may be ``unicode`` instances, subject to normal Python ``str`` to
0121 ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
0122 understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
0123 to cause an error.
0124
0125 If ``check_circular`` is ``False``, then the circular reference check
0126 for container types will be skipped and a circular reference will
0127 result in an ``OverflowError`` (or worse).
0128
0129 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
0130 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
0131 in strict compliance of the JSON specification, instead of using the
0132 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
0133
0134 If ``indent`` is a non-negative integer, then JSON array elements and object
0135 members will be pretty-printed with that indent level. An indent level
0136 of 0 will only insert newlines. ``None`` is the most compact representation.
0137
0138 If ``separators`` is an ``(item_separator, dict_separator)`` tuple
0139 then it will be used instead of the default ``(', ', ': ')`` separators.
0140 ``(',', ':')`` is the most compact JSON representation.
0141
0142 ``encoding`` is the character encoding for str instances, default is UTF-8.
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
0149 if (skipkeys is False and ensure_ascii is True and
0150 check_circular is True and allow_nan is True and
0151 cls is None and indent is None and separators is None and
0152 encoding == 'utf-8' and not kw):
0153 iterable = _default_encoder.iterencode(obj)
0154 else:
0155 if cls is None:
0156 cls = JSONEncoder
0157 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
0158 check_circular=check_circular, allow_nan=allow_nan, indent=indent,
0159 separators=separators, encoding=encoding, **kw).iterencode(obj)
0160
0161
0162 for chunk in iterable:
0163 fp.write(chunk)
0164
0165
0166def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
0167 allow_nan=True, cls=None, indent=None, separators=None,
0168 encoding='utf-8', **kw):
0169 """
0170 Serialize ``obj`` to a JSON formatted ``str``.
0171
0172 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
0173 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
0174 will be skipped instead of raising a ``TypeError``.
0175
0176 If ``ensure_ascii`` is ``False``, then the return value will be a
0177 ``unicode`` instance subject to normal Python ``str`` to ``unicode``
0178 coercion rules instead of being escaped to an ASCII ``str``.
0179
0180 If ``check_circular`` is ``False``, then the circular reference check
0181 for container types will be skipped and a circular reference will
0182 result in an ``OverflowError`` (or worse).
0183
0184 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
0185 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
0186 strict compliance of the JSON specification, instead of using the
0187 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
0188
0189 If ``indent`` is a non-negative integer, then JSON array elements and
0190 object members will be pretty-printed with that indent level. An indent
0191 level of 0 will only insert newlines. ``None`` is the most compact
0192 representation.
0193
0194 If ``separators`` is an ``(item_separator, dict_separator)`` tuple
0195 then it will be used instead of the default ``(', ', ': ')`` separators.
0196 ``(',', ':')`` is the most compact JSON representation.
0197
0198 ``encoding`` is the character encoding for str instances, default is UTF-8.
0199
0200 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
0201 ``.default()`` method to serialize additional types), specify it with
0202 the ``cls`` kwarg.
0203 """
0204
0205 if (skipkeys is False and ensure_ascii is True and
0206 check_circular is True and allow_nan is True and
0207 cls is None and indent is None and separators is None and
0208 encoding == 'utf-8' and not kw):
0209 return _default_encoder.encode(obj)
0210 if cls is None:
0211 cls = JSONEncoder
0212 return cls(
0213 skipkeys=skipkeys, ensure_ascii=ensure_ascii,
0214 check_circular=check_circular, allow_nan=allow_nan, indent=indent,
0215 separators=separators, encoding=encoding,
0216 **kw).encode(obj)
0217
0218_default_decoder = JSONDecoder(encoding=None, object_hook=None)
0219
0220def load(fp, encoding=None, cls=None, object_hook=None, **kw):
0221 """
0222 Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
0223 a JSON document) to a Python object.
0224
0225 If the contents of ``fp`` is encoded with an ASCII based encoding other
0226 than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
0227 be specified. Encodings that are not ASCII based (such as UCS-2) are
0228 not allowed, and should be wrapped with
0229 ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
0230 object and passed to ``loads()``
0231
0232 ``object_hook`` is an optional function that will be called with the
0233 result of any object literal decode (a ``dict``). The return value of
0234 ``object_hook`` will be used instead of the ``dict``. This feature
0235 can be used to implement custom decoders (e.g. JSON-RPC class hinting).
0236
0237 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
0238 kwarg.
0239 """
0240 return loads(fp.read(),
0241 encoding=encoding, cls=cls, object_hook=object_hook, **kw)
0242
0243def loads(s, encoding=None, cls=None, object_hook=None, **kw):
0244 """
0245 Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
0246 document) to a Python object.
0247
0248 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
0249 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
0250 must be specified. Encodings that are not ASCII based (such as UCS-2)
0251 are not allowed and should be decoded to ``unicode`` first.
0252
0253 ``object_hook`` is an optional function that will be called with the
0254 result of any object literal decode (a ``dict``). The return value of
0255 ``object_hook`` will be used instead of the ``dict``. This feature
0256 can be used to implement custom decoders (e.g. JSON-RPC class hinting).
0257
0258 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
0259 kwarg.
0260 """
0261 if cls is None and encoding is None and object_hook is None and not kw:
0262 return _default_decoder.decode(s)
0263 if cls is None:
0264 cls = JSONDecoder
0265 if object_hook is not None:
0266 kw['object_hook'] = object_hook
0267 return cls(encoding=encoding, **kw).decode(s)
0268
0269def read(s):
0270 """
0271 json-py API compatibility hook. Use loads(s) instead.
0272 """
0273 import warnings
0274 warnings.warn("simplejson.loads(s) should be used instead of read(s)",
0275 DeprecationWarning)
0276 return loads(s)
0277
0278def write(obj):
0279 """
0280 json-py API compatibility hook. Use dumps(s) instead.
0281 """
0282 import warnings
0283 warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
0284 DeprecationWarning)
0285 return dumps(obj)