|
1 r""" |
|
2 A simple, fast, extensible JSON encoder and decoder |
|
3 |
|
4 JSON (JavaScript Object Notation) <http://json.org> is a subset of |
|
5 JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data |
|
6 interchange format. |
|
7 |
|
8 simplejson exposes an API familiar to uses of the standard library |
|
9 marshal and pickle modules. |
|
10 |
|
11 Encoding basic Python object hierarchies:: |
|
12 |
|
13 >>> import simplejson |
|
14 >>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) |
|
15 '["foo", {"bar": ["baz", null, 1.0, 2]}]' |
|
16 >>> print simplejson.dumps("\"foo\bar") |
|
17 "\"foo\bar" |
|
18 >>> print simplejson.dumps(u'\u1234') |
|
19 "\u1234" |
|
20 >>> print simplejson.dumps('\\') |
|
21 "\\" |
|
22 >>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) |
|
23 {"a": 0, "b": 0, "c": 0} |
|
24 >>> from StringIO import StringIO |
|
25 >>> io = StringIO() |
|
26 >>> simplejson.dump(['streaming API'], io) |
|
27 >>> io.getvalue() |
|
28 '["streaming API"]' |
|
29 |
|
30 Compact encoding:: |
|
31 |
|
32 >>> import simplejson |
|
33 >>> simplejson.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) |
|
34 '[1,2,3,{"4":5,"6":7}]' |
|
35 |
|
36 Pretty printing:: |
|
37 |
|
38 >>> import simplejson |
|
39 >>> print simplejson.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) |
|
40 { |
|
41 "4": 5, |
|
42 "6": 7 |
|
43 } |
|
44 |
|
45 Decoding JSON:: |
|
46 |
|
47 >>> import simplejson |
|
48 >>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') |
|
49 [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] |
|
50 >>> simplejson.loads('"\\"foo\\bar"') |
|
51 u'"foo\x08ar' |
|
52 >>> from StringIO import StringIO |
|
53 >>> io = StringIO('["streaming API"]') |
|
54 >>> simplejson.load(io) |
|
55 [u'streaming API'] |
|
56 |
|
57 Specializing JSON object decoding:: |
|
58 |
|
59 >>> import simplejson |
|
60 >>> def as_complex(dct): |
|
61 ... if '__complex__' in dct: |
|
62 ... return complex(dct['real'], dct['imag']) |
|
63 ... return dct |
|
64 ... |
|
65 >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}', |
|
66 ... object_hook=as_complex) |
|
67 (1+2j) |
|
68 |
|
69 Extending JSONEncoder:: |
|
70 |
|
71 >>> import simplejson |
|
72 >>> class ComplexEncoder(simplejson.JSONEncoder): |
|
73 ... def default(self, obj): |
|
74 ... if isinstance(obj, complex): |
|
75 ... return [obj.real, obj.imag] |
|
76 ... return simplejson.JSONEncoder.default(self, obj) |
|
77 ... |
|
78 >>> dumps(2 + 1j, cls=ComplexEncoder) |
|
79 '[2.0, 1.0]' |
|
80 >>> ComplexEncoder().encode(2 + 1j) |
|
81 '[2.0, 1.0]' |
|
82 >>> list(ComplexEncoder().iterencode(2 + 1j)) |
|
83 ['[', '2.0', ', ', '1.0', ']'] |
|
84 |
|
85 |
|
86 Note that the JSON produced by this module's default settings |
|
87 is a subset of YAML, so it may be used as a serializer for that as well. |
|
88 """ |
|
89 __version__ = '1.5' |
|
90 __all__ = [ |
|
91 'dump', 'dumps', 'load', 'loads', |
|
92 'JSONDecoder', 'JSONEncoder', |
|
93 ] |
|
94 |
|
95 from django.utils.simplejson.decoder import JSONDecoder |
|
96 from django.utils.simplejson.encoder import JSONEncoder |
|
97 |
|
98 def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, |
|
99 allow_nan=True, cls=None, indent=None, **kw): |
|
100 """ |
|
101 Serialize ``obj`` as a JSON formatted stream to ``fp`` (a |
|
102 ``.write()``-supporting file-like object). |
|
103 |
|
104 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types |
|
105 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) |
|
106 will be skipped instead of raising a ``TypeError``. |
|
107 |
|
108 If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp`` |
|
109 may be ``unicode`` instances, subject to normal Python ``str`` to |
|
110 ``unicode`` coercion rules. Unless ``fp.write()`` explicitly |
|
111 understands ``unicode`` (as in ``codecs.getwriter()``) this is likely |
|
112 to cause an error. |
|
113 |
|
114 If ``check_circular`` is ``False``, then the circular reference check |
|
115 for container types will be skipped and a circular reference will |
|
116 result in an ``OverflowError`` (or worse). |
|
117 |
|
118 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to |
|
119 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) |
|
120 in strict compliance of the JSON specification, instead of using the |
|
121 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). |
|
122 |
|
123 If ``indent`` is a non-negative integer, then JSON array elements and object |
|
124 members will be pretty-printed with that indent level. An indent level |
|
125 of 0 will only insert newlines. ``None`` is the most compact representation. |
|
126 |
|
127 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the |
|
128 ``.default()`` method to serialize additional types), specify it with |
|
129 the ``cls`` kwarg. |
|
130 """ |
|
131 if cls is None: |
|
132 cls = JSONEncoder |
|
133 iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, |
|
134 check_circular=check_circular, allow_nan=allow_nan, indent=indent, |
|
135 **kw).iterencode(obj) |
|
136 # could accelerate with writelines in some versions of Python, at |
|
137 # a debuggability cost |
|
138 for chunk in iterable: |
|
139 fp.write(chunk) |
|
140 |
|
141 def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, |
|
142 allow_nan=True, cls=None, indent=None, separators=None, **kw): |
|
143 """ |
|
144 Serialize ``obj`` to a JSON formatted ``str``. |
|
145 |
|
146 If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types |
|
147 (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) |
|
148 will be skipped instead of raising a ``TypeError``. |
|
149 |
|
150 If ``ensure_ascii`` is ``False``, then the return value will be a |
|
151 ``unicode`` instance subject to normal Python ``str`` to ``unicode`` |
|
152 coercion rules instead of being escaped to an ASCII ``str``. |
|
153 |
|
154 If ``check_circular`` is ``False``, then the circular reference check |
|
155 for container types will be skipped and a circular reference will |
|
156 result in an ``OverflowError`` (or worse). |
|
157 |
|
158 If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to |
|
159 serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in |
|
160 strict compliance of the JSON specification, instead of using the |
|
161 JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). |
|
162 |
|
163 If ``indent`` is a non-negative integer, then JSON array elements and |
|
164 object members will be pretty-printed with that indent level. An indent |
|
165 level of 0 will only insert newlines. ``None`` is the most compact |
|
166 representation. |
|
167 |
|
168 If ``separators`` is an ``(item_separator, dict_separator)`` tuple |
|
169 then it will be used instead of the default ``(', ', ': ')`` separators. |
|
170 ``(',', ':')`` is the most compact JSON representation. |
|
171 |
|
172 To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the |
|
173 ``.default()`` method to serialize additional types), specify it with |
|
174 the ``cls`` kwarg. |
|
175 """ |
|
176 if cls is None: |
|
177 cls = JSONEncoder |
|
178 return cls( |
|
179 skipkeys=skipkeys, ensure_ascii=ensure_ascii, |
|
180 check_circular=check_circular, allow_nan=allow_nan, indent=indent, |
|
181 separators=separators, |
|
182 **kw).encode(obj) |
|
183 |
|
184 def load(fp, encoding=None, cls=None, object_hook=None, **kw): |
|
185 """ |
|
186 Deserialize ``fp`` (a ``.read()``-supporting file-like object containing |
|
187 a JSON document) to a Python object. |
|
188 |
|
189 If the contents of ``fp`` is encoded with an ASCII based encoding other |
|
190 than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must |
|
191 be specified. Encodings that are not ASCII based (such as UCS-2) are |
|
192 not allowed, and should be wrapped with |
|
193 ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` |
|
194 object and passed to ``loads()`` |
|
195 |
|
196 ``object_hook`` is an optional function that will be called with the |
|
197 result of any object literal decode (a ``dict``). The return value of |
|
198 ``object_hook`` will be used instead of the ``dict``. This feature |
|
199 can be used to implement custom decoders (e.g. JSON-RPC class hinting). |
|
200 |
|
201 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` |
|
202 kwarg. |
|
203 """ |
|
204 if cls is None: |
|
205 cls = JSONDecoder |
|
206 if object_hook is not None: |
|
207 kw['object_hook'] = object_hook |
|
208 return cls(encoding=encoding, **kw).decode(fp.read()) |
|
209 |
|
210 def loads(s, encoding=None, cls=None, object_hook=None, **kw): |
|
211 """ |
|
212 Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON |
|
213 document) to a Python object. |
|
214 |
|
215 If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding |
|
216 other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name |
|
217 must be specified. Encodings that are not ASCII based (such as UCS-2) |
|
218 are not allowed and should be decoded to ``unicode`` first. |
|
219 |
|
220 ``object_hook`` is an optional function that will be called with the |
|
221 result of any object literal decode (a ``dict``). The return value of |
|
222 ``object_hook`` will be used instead of the ``dict``. This feature |
|
223 can be used to implement custom decoders (e.g. JSON-RPC class hinting). |
|
224 |
|
225 To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` |
|
226 kwarg. |
|
227 """ |
|
228 if cls is None: |
|
229 cls = JSONDecoder |
|
230 if object_hook is not None: |
|
231 kw['object_hook'] = object_hook |
|
232 return cls(encoding=encoding, **kw).decode(s) |
|
233 |
|
234 def read(s): |
|
235 """ |
|
236 json-py API compatibility hook. Use loads(s) instead. |
|
237 """ |
|
238 import warnings |
|
239 warnings.warn("simplejson.loads(s) should be used instead of read(s)", |
|
240 DeprecationWarning) |
|
241 return loads(s) |
|
242 |
|
243 def write(obj): |
|
244 """ |
|
245 json-py API compatibility hook. Use dumps(s) instead. |
|
246 """ |
|
247 import warnings |
|
248 warnings.warn("simplejson.dumps(s) should be used instead of write(s)", |
|
249 DeprecationWarning) |
|
250 return dumps(obj) |
|
251 |
|
252 |