PageRenderTime 314ms CodeModel.GetById 297ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

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

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