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