addon-sdk/source/python-lib/simplejson/__init__.py

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/addon-sdk/source/python-lib/simplejson/__init__.py	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,376 @@
     1.4 +r"""
     1.5 +A simple, fast, extensible JSON encoder and decoder
     1.6 +
     1.7 +JSON (JavaScript Object Notation) <http://json.org> is a subset of
     1.8 +JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
     1.9 +interchange format.
    1.10 +
    1.11 +simplejson exposes an API familiar to uses of the standard library
    1.12 +marshal and pickle modules.
    1.13 +
    1.14 +Encoding basic Python object hierarchies::
    1.15 +    
    1.16 +    >>> import simplejson
    1.17 +    >>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
    1.18 +    '["foo", {"bar": ["baz", null, 1.0, 2]}]'
    1.19 +    >>> print simplejson.dumps("\"foo\bar")
    1.20 +    "\"foo\bar"
    1.21 +    >>> print simplejson.dumps(u'\u1234')
    1.22 +    "\u1234"
    1.23 +    >>> print simplejson.dumps('\\')
    1.24 +    "\\"
    1.25 +    >>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
    1.26 +    {"a": 0, "b": 0, "c": 0}
    1.27 +    >>> from StringIO import StringIO
    1.28 +    >>> io = StringIO()
    1.29 +    >>> simplejson.dump(['streaming API'], io)
    1.30 +    >>> io.getvalue()
    1.31 +    '["streaming API"]'
    1.32 +
    1.33 +Compact encoding::
    1.34 +
    1.35 +    >>> import simplejson
    1.36 +    >>> simplejson.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
    1.37 +    '[1,2,3,{"4":5,"6":7}]'
    1.38 +
    1.39 +Pretty printing::
    1.40 +
    1.41 +    >>> import simplejson
    1.42 +    >>> print simplejson.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
    1.43 +    {
    1.44 +        "4": 5, 
    1.45 +        "6": 7
    1.46 +    }
    1.47 +
    1.48 +Decoding JSON::
    1.49 +    
    1.50 +    >>> import simplejson
    1.51 +    >>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
    1.52 +    [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
    1.53 +    >>> simplejson.loads('"\\"foo\\bar"')
    1.54 +    u'"foo\x08ar'
    1.55 +    >>> from StringIO import StringIO
    1.56 +    >>> io = StringIO('["streaming API"]')
    1.57 +    >>> simplejson.load(io)
    1.58 +    [u'streaming API']
    1.59 +
    1.60 +Specializing JSON object decoding::
    1.61 +
    1.62 +    >>> import simplejson
    1.63 +    >>> def as_complex(dct):
    1.64 +    ...     if '__complex__' in dct:
    1.65 +    ...         return complex(dct['real'], dct['imag'])
    1.66 +    ...     return dct
    1.67 +    ... 
    1.68 +    >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',
    1.69 +    ...     object_hook=as_complex)
    1.70 +    (1+2j)
    1.71 +    >>> import decimal
    1.72 +    >>> simplejson.loads('1.1', parse_float=decimal.Decimal)
    1.73 +    Decimal("1.1")
    1.74 +
    1.75 +Extending JSONEncoder::
    1.76 +    
    1.77 +    >>> import simplejson
    1.78 +    >>> class ComplexEncoder(simplejson.JSONEncoder):
    1.79 +    ...     def default(self, obj):
    1.80 +    ...         if isinstance(obj, complex):
    1.81 +    ...             return [obj.real, obj.imag]
    1.82 +    ...         return simplejson.JSONEncoder.default(self, obj)
    1.83 +    ... 
    1.84 +    >>> dumps(2 + 1j, cls=ComplexEncoder)
    1.85 +    '[2.0, 1.0]'
    1.86 +    >>> ComplexEncoder().encode(2 + 1j)
    1.87 +    '[2.0, 1.0]'
    1.88 +    >>> list(ComplexEncoder().iterencode(2 + 1j))
    1.89 +    ['[', '2.0', ', ', '1.0', ']']
    1.90 +    
    1.91 +
    1.92 +Using simplejson from the shell to validate and
    1.93 +pretty-print::
    1.94 +    
    1.95 +    $ echo '{"json":"obj"}' | python -msimplejson.tool
    1.96 +    {
    1.97 +        "json": "obj"
    1.98 +    }
    1.99 +    $ echo '{ 1.2:3.4}' | python -msimplejson.tool
   1.100 +    Expecting property name: line 1 column 2 (char 2)
   1.101 +
   1.102 +Note that the JSON produced by this module's default settings
   1.103 +is a subset of YAML, so it may be used as a serializer for that as well.
   1.104 +"""
   1.105 +__version__ = '1.9.2'
   1.106 +__all__ = [
   1.107 +    'dump', 'dumps', 'load', 'loads',
   1.108 +    'JSONDecoder', 'JSONEncoder',
   1.109 +]
   1.110 +
   1.111 +if __name__ == '__main__':
   1.112 +    import warnings
   1.113 +    warnings.warn('python -msimplejson is deprecated, use python -msiplejson.tool', DeprecationWarning)
   1.114 +    from simplejson.decoder import JSONDecoder
   1.115 +    from simplejson.encoder import JSONEncoder
   1.116 +else:
   1.117 +    from decoder import JSONDecoder
   1.118 +    from encoder import JSONEncoder
   1.119 +
   1.120 +_default_encoder = JSONEncoder(
   1.121 +    skipkeys=False,
   1.122 +    ensure_ascii=True,
   1.123 +    check_circular=True,
   1.124 +    allow_nan=True,
   1.125 +    indent=None,
   1.126 +    separators=None,
   1.127 +    encoding='utf-8',
   1.128 +    default=None,
   1.129 +)
   1.130 +
   1.131 +def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
   1.132 +        allow_nan=True, cls=None, indent=None, separators=None,
   1.133 +        encoding='utf-8', default=None, **kw):
   1.134 +    """
   1.135 +    Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
   1.136 +    ``.write()``-supporting file-like object).
   1.137 +
   1.138 +    If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
   1.139 +    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 
   1.140 +    will be skipped instead of raising a ``TypeError``.
   1.141 +
   1.142 +    If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
   1.143 +    may be ``unicode`` instances, subject to normal Python ``str`` to
   1.144 +    ``unicode`` coercion rules. Unless ``fp.write()`` explicitly
   1.145 +    understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
   1.146 +    to cause an error.
   1.147 +
   1.148 +    If ``check_circular`` is ``False``, then the circular reference check
   1.149 +    for container types will be skipped and a circular reference will
   1.150 +    result in an ``OverflowError`` (or worse).
   1.151 +
   1.152 +    If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
   1.153 +    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
   1.154 +    in strict compliance of the JSON specification, instead of using the
   1.155 +    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
   1.156 +
   1.157 +    If ``indent`` is a non-negative integer, then JSON array elements and object
   1.158 +    members will be pretty-printed with that indent level. An indent level
   1.159 +    of 0 will only insert newlines. ``None`` is the most compact representation.
   1.160 +
   1.161 +    If ``separators`` is an ``(item_separator, dict_separator)`` tuple
   1.162 +    then it will be used instead of the default ``(', ', ': ')`` separators.
   1.163 +    ``(',', ':')`` is the most compact JSON representation.
   1.164 +
   1.165 +    ``encoding`` is the character encoding for str instances, default is UTF-8.
   1.166 +
   1.167 +    ``default(obj)`` is a function that should return a serializable version
   1.168 +    of obj or raise TypeError. The default simply raises TypeError.
   1.169 +
   1.170 +    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
   1.171 +    ``.default()`` method to serialize additional types), specify it with
   1.172 +    the ``cls`` kwarg.
   1.173 +    """
   1.174 +    # cached encoder
   1.175 +    if (skipkeys is False and ensure_ascii is True and
   1.176 +        check_circular is True and allow_nan is True and
   1.177 +        cls is None and indent is None and separators is None and
   1.178 +        encoding == 'utf-8' and default is None and not kw):
   1.179 +        iterable = _default_encoder.iterencode(obj)
   1.180 +    else:
   1.181 +        if cls is None:
   1.182 +            cls = JSONEncoder
   1.183 +        iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
   1.184 +            check_circular=check_circular, allow_nan=allow_nan, indent=indent,
   1.185 +            separators=separators, encoding=encoding,
   1.186 +            default=default, **kw).iterencode(obj)
   1.187 +    # could accelerate with writelines in some versions of Python, at
   1.188 +    # a debuggability cost
   1.189 +    for chunk in iterable:
   1.190 +        fp.write(chunk)
   1.191 +
   1.192 +
   1.193 +def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
   1.194 +        allow_nan=True, cls=None, indent=None, separators=None,
   1.195 +        encoding='utf-8', default=None, **kw):
   1.196 +    """
   1.197 +    Serialize ``obj`` to a JSON formatted ``str``.
   1.198 +
   1.199 +    If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
   1.200 +    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) 
   1.201 +    will be skipped instead of raising a ``TypeError``.
   1.202 +
   1.203 +    If ``ensure_ascii`` is ``False``, then the return value will be a
   1.204 +    ``unicode`` instance subject to normal Python ``str`` to ``unicode``
   1.205 +    coercion rules instead of being escaped to an ASCII ``str``.
   1.206 +
   1.207 +    If ``check_circular`` is ``False``, then the circular reference check
   1.208 +    for container types will be skipped and a circular reference will
   1.209 +    result in an ``OverflowError`` (or worse).
   1.210 +
   1.211 +    If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
   1.212 +    serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
   1.213 +    strict compliance of the JSON specification, instead of using the
   1.214 +    JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
   1.215 +
   1.216 +    If ``indent`` is a non-negative integer, then JSON array elements and
   1.217 +    object members will be pretty-printed with that indent level. An indent
   1.218 +    level of 0 will only insert newlines. ``None`` is the most compact
   1.219 +    representation.
   1.220 +
   1.221 +    If ``separators`` is an ``(item_separator, dict_separator)`` tuple
   1.222 +    then it will be used instead of the default ``(', ', ': ')`` separators.
   1.223 +    ``(',', ':')`` is the most compact JSON representation.
   1.224 +
   1.225 +    ``encoding`` is the character encoding for str instances, default is UTF-8.
   1.226 +
   1.227 +    ``default(obj)`` is a function that should return a serializable version
   1.228 +    of obj or raise TypeError. The default simply raises TypeError.
   1.229 +
   1.230 +    To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
   1.231 +    ``.default()`` method to serialize additional types), specify it with
   1.232 +    the ``cls`` kwarg.
   1.233 +    """
   1.234 +    # cached encoder
   1.235 +    if (skipkeys is False and ensure_ascii is True and
   1.236 +        check_circular is True and allow_nan is True and
   1.237 +        cls is None and indent is None and separators is None and
   1.238 +        encoding == 'utf-8' and default is None and not kw):
   1.239 +        return _default_encoder.encode(obj)
   1.240 +    if cls is None:
   1.241 +        cls = JSONEncoder
   1.242 +    return cls(
   1.243 +        skipkeys=skipkeys, ensure_ascii=ensure_ascii,
   1.244 +        check_circular=check_circular, allow_nan=allow_nan, indent=indent,
   1.245 +        separators=separators, encoding=encoding, default=default,
   1.246 +        **kw).encode(obj)
   1.247 +
   1.248 +
   1.249 +_default_decoder = JSONDecoder(encoding=None, object_hook=None)
   1.250 +
   1.251 +
   1.252 +def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None,
   1.253 +        parse_int=None, parse_constant=None, **kw):
   1.254 +    """
   1.255 +    Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
   1.256 +    a JSON document) to a Python object.
   1.257 +
   1.258 +    If the contents of ``fp`` is encoded with an ASCII based encoding other
   1.259 +    than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
   1.260 +    be specified. Encodings that are not ASCII based (such as UCS-2) are
   1.261 +    not allowed, and should be wrapped with
   1.262 +    ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
   1.263 +    object and passed to ``loads()``
   1.264 +
   1.265 +    ``object_hook`` is an optional function that will be called with the
   1.266 +    result of any object literal decode (a ``dict``). The return value of
   1.267 +    ``object_hook`` will be used instead of the ``dict``. This feature
   1.268 +    can be used to implement custom decoders (e.g. JSON-RPC class hinting).
   1.269 +    
   1.270 +    To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
   1.271 +    kwarg.
   1.272 +    """
   1.273 +    return loads(fp.read(),
   1.274 +        encoding=encoding, cls=cls, object_hook=object_hook,
   1.275 +        parse_float=parse_float, parse_int=parse_int,
   1.276 +        parse_constant=parse_constant, **kw)
   1.277 +
   1.278 +
   1.279 +def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
   1.280 +        parse_int=None, parse_constant=None, **kw):
   1.281 +    """
   1.282 +    Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
   1.283 +    document) to a Python object.
   1.284 +
   1.285 +    If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
   1.286 +    other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
   1.287 +    must be specified. Encodings that are not ASCII based (such as UCS-2)
   1.288 +    are not allowed and should be decoded to ``unicode`` first.
   1.289 +
   1.290 +    ``object_hook`` is an optional function that will be called with the
   1.291 +    result of any object literal decode (a ``dict``). The return value of
   1.292 +    ``object_hook`` will be used instead of the ``dict``. This feature
   1.293 +    can be used to implement custom decoders (e.g. JSON-RPC class hinting).
   1.294 +
   1.295 +    ``parse_float``, if specified, will be called with the string
   1.296 +    of every JSON float to be decoded. By default this is equivalent to
   1.297 +    float(num_str). This can be used to use another datatype or parser
   1.298 +    for JSON floats (e.g. decimal.Decimal).
   1.299 +
   1.300 +    ``parse_int``, if specified, will be called with the string
   1.301 +    of every JSON int to be decoded. By default this is equivalent to
   1.302 +    int(num_str). This can be used to use another datatype or parser
   1.303 +    for JSON integers (e.g. float).
   1.304 +
   1.305 +    ``parse_constant``, if specified, will be called with one of the
   1.306 +    following strings: -Infinity, Infinity, NaN, null, true, false.
   1.307 +    This can be used to raise an exception if invalid JSON numbers
   1.308 +    are encountered.
   1.309 +
   1.310 +    To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
   1.311 +    kwarg.
   1.312 +    """
   1.313 +    if (cls is None and encoding is None and object_hook is None and
   1.314 +            parse_int is None and parse_float is None and
   1.315 +            parse_constant is None and not kw):
   1.316 +        return _default_decoder.decode(s)
   1.317 +    if cls is None:
   1.318 +        cls = JSONDecoder
   1.319 +    if object_hook is not None:
   1.320 +        kw['object_hook'] = object_hook
   1.321 +    if parse_float is not None:
   1.322 +        kw['parse_float'] = parse_float
   1.323 +    if parse_int is not None:
   1.324 +        kw['parse_int'] = parse_int
   1.325 +    if parse_constant is not None:
   1.326 +        kw['parse_constant'] = parse_constant
   1.327 +    return cls(encoding=encoding, **kw).decode(s)
   1.328 +
   1.329 +
   1.330 +#
   1.331 +# Compatibility cruft from other libraries
   1.332 +#
   1.333 +
   1.334 +
   1.335 +def decode(s):
   1.336 +    """
   1.337 +    demjson, python-cjson API compatibility hook. Use loads(s) instead.
   1.338 +    """
   1.339 +    import warnings
   1.340 +    warnings.warn("simplejson.loads(s) should be used instead of decode(s)",
   1.341 +        DeprecationWarning)
   1.342 +    return loads(s)
   1.343 +
   1.344 +
   1.345 +def encode(obj):
   1.346 +    """
   1.347 +    demjson, python-cjson compatibility hook. Use dumps(s) instead.
   1.348 +    """
   1.349 +    import warnings
   1.350 +    warnings.warn("simplejson.dumps(s) should be used instead of encode(s)",
   1.351 +        DeprecationWarning)
   1.352 +    return dumps(obj)
   1.353 +
   1.354 +
   1.355 +def read(s):
   1.356 +    """
   1.357 +    jsonlib, JsonUtils, python-json, json-py API compatibility hook.
   1.358 +    Use loads(s) instead.
   1.359 +    """
   1.360 +    import warnings
   1.361 +    warnings.warn("simplejson.loads(s) should be used instead of read(s)",
   1.362 +        DeprecationWarning)
   1.363 +    return loads(s)
   1.364 +
   1.365 +
   1.366 +def write(obj):
   1.367 +    """
   1.368 +    jsonlib, JsonUtils, python-json, json-py API compatibility hook.
   1.369 +    Use dumps(s) instead.
   1.370 +    """
   1.371 +    import warnings
   1.372 +    warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
   1.373 +        DeprecationWarning)
   1.374 +    return dumps(obj)
   1.375 +
   1.376 +
   1.377 +if __name__ == '__main__':
   1.378 +    import simplejson.tool
   1.379 +    simplejson.tool.main()

mercurial