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