PageRenderTime 43ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/jsonrpc/public/services/simplejson/__init__.py

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