__init__.py 23 KB

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