added the dependencies for the wikipedia exercises
[wikipedia-api-cdsw] / simplejson / __init__.py
1 r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
2 JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
3 interchange format.
4
5 :mod:`simplejson` exposes an API familiar to users of the standard library
6 :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
7 version of the :mod:`json` library contained in Python 2.6, but maintains
8 compatibility with Python 2.4 and Python 2.5 and (currently) has
9 significant performance advantages, even without using the optional C
10 extension for speedups.
11
12 Encoding basic Python object hierarchies::
13
14     >>> import simplejson as json
15     >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
16     '["foo", {"bar": ["baz", null, 1.0, 2]}]'
17     >>> print(json.dumps("\"foo\bar"))
18     "\"foo\bar"
19     >>> print(json.dumps(u'\u1234'))
20     "\u1234"
21     >>> print(json.dumps('\\'))
22     "\\"
23     >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
24     {"a": 0, "b": 0, "c": 0}
25     >>> from simplejson.compat import StringIO
26     >>> io = StringIO()
27     >>> json.dump(['streaming API'], io)
28     >>> io.getvalue()
29     '["streaming API"]'
30
31 Compact encoding::
32
33     >>> import simplejson as json
34     >>> obj = [1,2,3,{'4': 5, '6': 7}]
35     >>> json.dumps(obj, separators=(',',':'), sort_keys=True)
36     '[1,2,3,{"4":5,"6":7}]'
37
38 Pretty printing::
39
40     >>> import simplejson as json
41     >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent='    '))
42     {
43         "4": 5,
44         "6": 7
45     }
46
47 Decoding JSON::
48
49     >>> import simplejson as json
50     >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
51     >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj
52     True
53     >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar'
54     True
55     >>> from simplejson.compat import StringIO
56     >>> io = StringIO('["streaming API"]')
57     >>> json.load(io)[0] == 'streaming API'
58     True
59
60 Specializing JSON object decoding::
61
62     >>> import simplejson as json
63     >>> def as_complex(dct):
64     ...     if '__complex__' in dct:
65     ...         return complex(dct['real'], dct['imag'])
66     ...     return dct
67     ...
68     >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
69     ...     object_hook=as_complex)
70     (1+2j)
71     >>> from decimal import Decimal
72     >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
73     True
74
75 Specializing JSON object encoding::
76
77     >>> import simplejson as json
78     >>> def encode_complex(obj):
79     ...     if isinstance(obj, complex):
80     ...         return [obj.real, obj.imag]
81     ...     raise TypeError(repr(o) + " is not JSON serializable")
82     ...
83     >>> json.dumps(2 + 1j, default=encode_complex)
84     '[2.0, 1.0]'
85     >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j)
86     '[2.0, 1.0]'
87     >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j))
88     '[2.0, 1.0]'
89
90
91 Using simplejson.tool from the shell to validate and pretty-print::
92
93     $ echo '{"json":"obj"}' | python -m simplejson.tool
94     {
95         "json": "obj"
96     }
97     $ echo '{ 1.2:3.4}' | python -m simplejson.tool
98     Expecting property name: line 1 column 3 (char 2)
99 """
100 from __future__ import absolute_import
101 __version__ = '3.4.0'
102 __all__ = [
103     'dump', 'dumps', 'load', 'loads',
104     'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
105     'OrderedDict', 'simple_first',
106 ]
107
108 __author__ = 'Bob Ippolito <bob@redivi.com>'
109
110 from decimal import Decimal
111
112 from .scanner import JSONDecodeError
113 from .decoder import JSONDecoder
114 from .encoder import JSONEncoder, JSONEncoderForHTML
115 def _import_OrderedDict():
116     import collections
117     try:
118         return collections.OrderedDict
119     except AttributeError:
120         from . import ordered_dict
121         return ordered_dict.OrderedDict
122 OrderedDict = _import_OrderedDict()
123
124 def _import_c_make_encoder():
125     try:
126         from ._speedups import make_encoder
127         return make_encoder
128     except ImportError:
129         return None
130
131 _default_encoder = JSONEncoder(
132     skipkeys=False,
133     ensure_ascii=True,
134     check_circular=True,
135     allow_nan=True,
136     indent=None,
137     separators=None,
138     encoding='utf-8',
139     default=None,
140     use_decimal=True,
141     namedtuple_as_object=True,
142     tuple_as_array=True,
143     bigint_as_string=False,
144     item_sort_key=None,
145     for_json=False,
146     ignore_nan=False,
147 )
148
149 def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
150         allow_nan=True, cls=None, indent=None, separators=None,
151         encoding='utf-8', default=None, use_decimal=True,
152         namedtuple_as_object=True, tuple_as_array=True,
153         bigint_as_string=False, sort_keys=False, item_sort_key=None,
154         for_json=False, ignore_nan=False, **kw):
155     """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
156     ``.write()``-supporting file-like object).
157
158     If *skipkeys* is true then ``dict`` keys that are not basic types
159     (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
160     will be skipped instead of raising a ``TypeError``.
161
162     If *ensure_ascii* is false, then the some chunks written to ``fp``
163     may be ``unicode`` instances, subject to normal Python ``str`` to
164     ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
165     understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
166     to cause an error.
167
168     If *check_circular* is false, then the circular reference check
169     for container types will be skipped and a circular reference will
170     result in an ``OverflowError`` (or worse).
171
172     If *allow_nan* is false, then it will be a ``ValueError`` to
173     serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
174     in strict compliance of the original JSON specification, instead of using
175     the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). See
176     *ignore_nan* for ECMA-262 compliant behavior.
177
178     If *indent* is a string, then JSON array elements and object members
179     will be pretty-printed with a newline followed by that string repeated
180     for each level of nesting. ``None`` (the default) selects the most compact
181     representation without any newlines. For backwards compatibility with
182     versions of simplejson earlier than 2.1.0, an integer is also accepted
183     and is converted to a string with that many spaces.
184
185     If specified, *separators* should be an
186     ``(item_separator, key_separator)`` tuple.  The default is ``(', ', ': ')``
187     if *indent* is ``None`` and ``(',', ': ')`` otherwise.  To get the most
188     compact JSON representation, you should specify ``(',', ':')`` to eliminate
189     whitespace.
190
191     *encoding* is the character encoding for str instances, default is UTF-8.
192
193     *default(obj)* is a function that should return a serializable version
194     of obj or raise ``TypeError``. The default simply raises ``TypeError``.
195
196     If *use_decimal* is true (default: ``True``) then decimal.Decimal
197     will be natively serialized to JSON with full precision.
198
199     If *namedtuple_as_object* is true (default: ``True``),
200     :class:`tuple` subclasses with ``_asdict()`` methods will be encoded
201     as JSON objects.
202
203     If *tuple_as_array* is true (default: ``True``),
204     :class:`tuple` (and subclasses) will be encoded as JSON arrays.
205
206     If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher
207     or lower than -2**53 will be encoded as strings. This is to avoid the
208     rounding that happens in Javascript otherwise. Note that this is still a
209     lossy operation that will not round-trip correctly and should be used
210     sparingly.
211
212     If specified, *item_sort_key* is a callable used to sort the items in
213     each dictionary. This is useful if you want to sort items other than
214     in alphabetical order by key. This option takes precedence over
215     *sort_keys*.
216
217     If *sort_keys* is true (default: ``False``), the output of dictionaries
218     will be sorted by item.
219
220     If *for_json* is true (default: ``False``), objects with a ``for_json()``
221     method will use the return value of that method for encoding as JSON
222     instead of the object.
223
224     If *ignore_nan* is true (default: ``False``), then out of range
225     :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as
226     ``null`` in compliance with the ECMA-262 specification. If true, this will
227     override *allow_nan*.
228
229     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
230     ``.default()`` method to serialize additional types), specify it with
231     the ``cls`` kwarg. NOTE: You should use *default* or *for_json* instead
232     of subclassing whenever possible.
233
234     """
235     # cached encoder
236     if (not skipkeys and ensure_ascii and
237         check_circular and allow_nan and
238         cls is None and indent is None and separators is None and
239         encoding == 'utf-8' and default is None and use_decimal
240         and namedtuple_as_object and tuple_as_array
241         and not bigint_as_string and not item_sort_key
242         and not for_json and not ignore_nan and not kw):
243         iterable = _default_encoder.iterencode(obj)
244     else:
245         if cls is None:
246             cls = JSONEncoder
247         iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
248             check_circular=check_circular, allow_nan=allow_nan, indent=indent,
249             separators=separators, encoding=encoding,
250             default=default, use_decimal=use_decimal,
251             namedtuple_as_object=namedtuple_as_object,
252             tuple_as_array=tuple_as_array,
253             bigint_as_string=bigint_as_string,
254             sort_keys=sort_keys,
255             item_sort_key=item_sort_key,
256             for_json=for_json,
257             ignore_nan=ignore_nan,
258             **kw).iterencode(obj)
259     # could accelerate with writelines in some versions of Python, at
260     # a debuggability cost
261     for chunk in iterable:
262         fp.write(chunk)
263
264
265 def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
266         allow_nan=True, cls=None, indent=None, separators=None,
267         encoding='utf-8', default=None, use_decimal=True,
268         namedtuple_as_object=True, tuple_as_array=True,
269         bigint_as_string=False, sort_keys=False, item_sort_key=None,
270         for_json=False, ignore_nan=False, **kw):
271     """Serialize ``obj`` to a JSON formatted ``str``.
272
273     If ``skipkeys`` is false then ``dict`` keys that are not basic types
274     (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
275     will be skipped instead of raising a ``TypeError``.
276
277     If ``ensure_ascii`` is false, then the return value will be a
278     ``unicode`` instance subject to normal Python ``str`` to ``unicode``
279     coercion rules instead of being escaped to an ASCII ``str``.
280
281     If ``check_circular`` is false, then the circular reference check
282     for container types will be skipped and a circular reference will
283     result in an ``OverflowError`` (or worse).
284
285     If ``allow_nan`` is false, then it will be a ``ValueError`` to
286     serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
287     strict compliance of the JSON specification, instead of using the
288     JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
289
290     If ``indent`` is a string, then JSON array elements and object members
291     will be pretty-printed with a newline followed by that string repeated
292     for each level of nesting. ``None`` (the default) selects the most compact
293     representation without any newlines. For backwards compatibility with
294     versions of simplejson earlier than 2.1.0, an integer is also accepted
295     and is converted to a string with that many spaces.
296
297     If specified, ``separators`` should be an
298     ``(item_separator, key_separator)`` tuple.  The default is ``(', ', ': ')``
299     if *indent* is ``None`` and ``(',', ': ')`` otherwise.  To get the most
300     compact JSON representation, you should specify ``(',', ':')`` to eliminate
301     whitespace.
302
303     ``encoding`` is the character encoding for str instances, default is UTF-8.
304
305     ``default(obj)`` is a function that should return a serializable version
306     of obj or raise TypeError. The default simply raises TypeError.
307
308     If *use_decimal* is true (default: ``True``) then decimal.Decimal
309     will be natively serialized to JSON with full precision.
310
311     If *namedtuple_as_object* is true (default: ``True``),
312     :class:`tuple` subclasses with ``_asdict()`` methods will be encoded
313     as JSON objects.
314
315     If *tuple_as_array* is true (default: ``True``),
316     :class:`tuple` (and subclasses) will be encoded as JSON arrays.
317
318     If *bigint_as_string* is true (not the default), ints 2**53 and higher
319     or lower than -2**53 will be encoded as strings. This is to avoid the
320     rounding that happens in Javascript otherwise.
321
322     If specified, *item_sort_key* is a callable used to sort the items in
323     each dictionary. This is useful if you want to sort items other than
324     in alphabetical order by key. This option takes precendence over
325     *sort_keys*.
326
327     If *sort_keys* is true (default: ``False``), the output of dictionaries
328     will be sorted by item.
329
330     If *for_json* is true (default: ``False``), objects with a ``for_json()``
331     method will use the return value of that method for encoding as JSON
332     instead of the object.
333
334     If *ignore_nan* is true (default: ``False``), then out of range
335     :class:`float` values (``nan``, ``inf``, ``-inf``) will be serialized as
336     ``null`` in compliance with the ECMA-262 specification. If true, this will
337     override *allow_nan*.
338
339     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
340     ``.default()`` method to serialize additional types), specify it with
341     the ``cls`` kwarg. NOTE: You should use *default* instead of subclassing
342     whenever possible.
343
344     """
345     # cached encoder
346     if (not skipkeys and ensure_ascii and
347         check_circular and allow_nan and
348         cls is None and indent is None and separators is None and
349         encoding == 'utf-8' and default is None and use_decimal
350         and namedtuple_as_object and tuple_as_array
351         and not bigint_as_string and not sort_keys
352         and not item_sort_key and not for_json
353         and not ignore_nan and not kw):
354         return _default_encoder.encode(obj)
355     if cls is None:
356         cls = JSONEncoder
357     return cls(
358         skipkeys=skipkeys, ensure_ascii=ensure_ascii,
359         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
360         separators=separators, encoding=encoding, default=default,
361         use_decimal=use_decimal,
362         namedtuple_as_object=namedtuple_as_object,
363         tuple_as_array=tuple_as_array,
364         bigint_as_string=bigint_as_string,
365         sort_keys=sort_keys,
366         item_sort_key=item_sort_key,
367         for_json=for_json,
368         ignore_nan=ignore_nan,
369         **kw).encode(obj)
370
371
372 _default_decoder = JSONDecoder(encoding=None, object_hook=None,
373                                object_pairs_hook=None)
374
375
376 def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
377         parse_int=None, parse_constant=None, object_pairs_hook=None,
378         use_decimal=False, namedtuple_as_object=True, tuple_as_array=True,
379         **kw):
380     """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
381     a JSON document) to a Python object.
382
383     *encoding* determines the encoding used to interpret any
384     :class:`str` objects decoded by this instance (``'utf-8'`` by
385     default).  It has no effect when decoding :class:`unicode` objects.
386
387     Note that currently only encodings that are a superset of ASCII work,
388     strings of other encodings should be passed in as :class:`unicode`.
389
390     *object_hook*, if specified, will be called with the result of every
391     JSON object decoded and its return value will be used in place of the
392     given :class:`dict`.  This can be used to provide custom
393     deserializations (e.g. to support JSON-RPC class hinting).
394
395     *object_pairs_hook* is an optional function that will be called with
396     the result of any object literal decode with an ordered list of pairs.
397     The return value of *object_pairs_hook* will be used instead of the
398     :class:`dict`.  This feature can be used to implement custom decoders
399     that rely on the order that the key and value pairs are decoded (for
400     example, :func:`collections.OrderedDict` will remember the order of
401     insertion). If *object_hook* is also defined, the *object_pairs_hook*
402     takes priority.
403
404     *parse_float*, if specified, will be called with the string of every
405     JSON float to be decoded.  By default, this is equivalent to
406     ``float(num_str)``. This can be used to use another datatype or parser
407     for JSON floats (e.g. :class:`decimal.Decimal`).
408
409     *parse_int*, if specified, will be called with the string of every
410     JSON int to be decoded.  By default, this is equivalent to
411     ``int(num_str)``.  This can be used to use another datatype or parser
412     for JSON integers (e.g. :class:`float`).
413
414     *parse_constant*, if specified, will be called with one of the
415     following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.  This
416     can be used to raise an exception if invalid JSON numbers are
417     encountered.
418
419     If *use_decimal* is true (default: ``False``) then it implies
420     parse_float=decimal.Decimal for parity with ``dump``.
421
422     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
423     kwarg. NOTE: You should use *object_hook* or *object_pairs_hook* instead
424     of subclassing whenever possible.
425
426     """
427     return loads(fp.read(),
428         encoding=encoding, cls=cls, object_hook=object_hook,
429         parse_float=parse_float, parse_int=parse_int,
430         parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,
431         use_decimal=use_decimal, **kw)
432
433
434 def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
435         parse_int=None, parse_constant=None, object_pairs_hook=None,
436         use_decimal=False, **kw):
437     """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
438     document) to a Python object.
439
440     *encoding* determines the encoding used to interpret any
441     :class:`str` objects decoded by this instance (``'utf-8'`` by
442     default).  It has no effect when decoding :class:`unicode` objects.
443
444     Note that currently only encodings that are a superset of ASCII work,
445     strings of other encodings should be passed in as :class:`unicode`.
446
447     *object_hook*, if specified, will be called with the result of every
448     JSON object decoded and its return value will be used in place of the
449     given :class:`dict`.  This can be used to provide custom
450     deserializations (e.g. to support JSON-RPC class hinting).
451
452     *object_pairs_hook* is an optional function that will be called with
453     the result of any object literal decode with an ordered list of pairs.
454     The return value of *object_pairs_hook* will be used instead of the
455     :class:`dict`.  This feature can be used to implement custom decoders
456     that rely on the order that the key and value pairs are decoded (for
457     example, :func:`collections.OrderedDict` will remember the order of
458     insertion). If *object_hook* is also defined, the *object_pairs_hook*
459     takes priority.
460
461     *parse_float*, if specified, will be called with the string of every
462     JSON float to be decoded.  By default, this is equivalent to
463     ``float(num_str)``. This can be used to use another datatype or parser
464     for JSON floats (e.g. :class:`decimal.Decimal`).
465
466     *parse_int*, if specified, will be called with the string of every
467     JSON int to be decoded.  By default, this is equivalent to
468     ``int(num_str)``.  This can be used to use another datatype or parser
469     for JSON integers (e.g. :class:`float`).
470
471     *parse_constant*, if specified, will be called with one of the
472     following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.  This
473     can be used to raise an exception if invalid JSON numbers are
474     encountered.
475
476     If *use_decimal* is true (default: ``False``) then it implies
477     parse_float=decimal.Decimal for parity with ``dump``.
478
479     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
480     kwarg. NOTE: You should use *object_hook* or *object_pairs_hook* instead
481     of subclassing whenever possible.
482
483     """
484     if (cls is None and encoding is None and object_hook is None and
485             parse_int is None and parse_float is None and
486             parse_constant is None and object_pairs_hook is None
487             and not use_decimal and not kw):
488         return _default_decoder.decode(s)
489     if cls is None:
490         cls = JSONDecoder
491     if object_hook is not None:
492         kw['object_hook'] = object_hook
493     if object_pairs_hook is not None:
494         kw['object_pairs_hook'] = object_pairs_hook
495     if parse_float is not None:
496         kw['parse_float'] = parse_float
497     if parse_int is not None:
498         kw['parse_int'] = parse_int
499     if parse_constant is not None:
500         kw['parse_constant'] = parse_constant
501     if use_decimal:
502         if parse_float is not None:
503             raise TypeError("use_decimal=True implies parse_float=Decimal")
504         kw['parse_float'] = Decimal
505     return cls(encoding=encoding, **kw).decode(s)
506
507
508 def _toggle_speedups(enabled):
509     from . import decoder as dec
510     from . import encoder as enc
511     from . import scanner as scan
512     c_make_encoder = _import_c_make_encoder()
513     if enabled:
514         dec.scanstring = dec.c_scanstring or dec.py_scanstring
515         enc.c_make_encoder = c_make_encoder
516         enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or
517             enc.py_encode_basestring_ascii)
518         scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner
519     else:
520         dec.scanstring = dec.py_scanstring
521         enc.c_make_encoder = None
522         enc.encode_basestring_ascii = enc.py_encode_basestring_ascii
523         scan.make_scanner = scan.py_make_scanner
524     dec.make_scanner = scan.make_scanner
525     global _default_decoder
526     _default_decoder = JSONDecoder(
527         encoding=None,
528         object_hook=None,
529         object_pairs_hook=None,
530     )
531     global _default_encoder
532     _default_encoder = JSONEncoder(
533        skipkeys=False,
534        ensure_ascii=True,
535        check_circular=True,
536        allow_nan=True,
537        indent=None,
538        separators=None,
539        encoding='utf-8',
540        default=None,
541    )
542
543 def simple_first(kv):
544     """Helper function to pass to item_sort_key to sort simple
545     elements to the top, then container elements.
546     """
547     return (isinstance(kv[1], (list, dict, tuple)), kv[0])

Benjamin Mako Hill || Want to submit a patch?