diff options
Diffstat (limited to 'Lib/json/__init__.py')
| -rw-r--r-- | Lib/json/__init__.py | 99 |
1 files changed, 40 insertions, 59 deletions
diff --git a/Lib/json/__init__.py b/Lib/json/__init__.py index d6a45d3..44f49c4 100644 --- a/Lib/json/__init__.py +++ b/Lib/json/__init__.py @@ -14,15 +14,15 @@ Encoding basic Python object hierarchies:: >>> import json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' - >>> print json.dumps("\"foo\bar") + >>> print(json.dumps("\"foo\bar")) "\"foo\bar" - >>> print json.dumps(u'\u1234') + >>> print(json.dumps('\u1234')) "\u1234" - >>> print json.dumps('\\') + >>> print(json.dumps('\\')) "\\" - >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) + >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) {"a": 0, "b": 0, "c": 0} - >>> from StringIO import StringIO + >>> from io import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() @@ -31,14 +31,16 @@ Encoding basic Python object hierarchies:: Compact encoding:: >>> import json - >>> json.dumps([1,2,3,{'4': 5, '6': 7}], sort_keys=True, separators=(',',':')) + >>> from collections import OrderedDict + >>> mydict = OrderedDict([('4', 5), ('6', 7)]) + >>> json.dumps([1,2,3,mydict], separators=(',', ':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import json - >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, - ... indent=4, separators=(',', ': ')) + >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, + ... indent=4, separators=(',', ': '))) { "4": 5, "6": 7 @@ -47,12 +49,12 @@ Pretty printing:: Decoding JSON:: >>> import json - >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] + >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True - >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' + >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar' True - >>> from StringIO import StringIO + >>> from io import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True @@ -115,28 +117,22 @@ _default_encoder = JSONEncoder( allow_nan=True, indent=None, separators=None, - encoding='utf-8', default=None, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, - encoding='utf-8', default=None, sort_keys=False, **kw): + default=None, sort_keys=False, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is true then ``dict`` keys that are not basic types - (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) - will be skipped instead of raising a ``TypeError``. - - If ``ensure_ascii`` is true (the default), all non-ASCII characters in the - output are escaped with ``\uXXXX`` sequences, and the result is a ``str`` - instance consisting of ASCII characters only. If ``ensure_ascii`` is - ``False``, some chunks written to ``fp`` may be ``unicode`` instances. - This usually happens because the input contains unicode strings or the - ``encoding`` parameter is used. Unless ``fp.write()`` explicitly - understands ``unicode`` (as in ``codecs.getwriter``) this is likely to - cause an error. + (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped + instead of raising a ``TypeError``. + + If ``ensure_ascii`` is false, then the strings written to ``fp`` can + contain non-ASCII characters if they appear in strings contained in + ``obj``. Otherwise, all such characters are escaped in JSON strings. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will @@ -158,8 +154,6 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. - ``encoding`` is the character encoding for str instances, default is UTF-8. - ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. @@ -175,14 +169,14 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and - encoding == 'utf-8' and default is None and not sort_keys and not kw): + default is None and not sort_keys and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, - separators=separators, encoding=encoding, + separators=separators, default=default, sort_keys=sort_keys, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost @@ -192,15 +186,16 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, - encoding='utf-8', default=None, sort_keys=False, **kw): + default=None, sort_keys=False, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is false then ``dict`` keys that are not basic types - (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) - will be skipped instead of raising a ``TypeError``. + (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped + instead of raising a ``TypeError``. - If ``ensure_ascii`` is false, all non-ASCII characters are not escaped, and - the return value may be a ``unicode`` instance. See ``dump`` for details. + If ``ensure_ascii`` is false, then the return value can contain non-ASCII + characters if they appear in strings contained in ``obj``. Otherwise, all + such characters are escaped in JSON strings. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will @@ -222,8 +217,6 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. - ``encoding`` is the character encoding for str instances, default is UTF-8. - ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. @@ -239,33 +232,25 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and - encoding == 'utf-8' and default is None and not sort_keys and not kw): + default is None and not sort_keys and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, - separators=separators, encoding=encoding, default=default, - sort_keys=sort_keys, **kw).encode(obj) + separators=separators, default=default, sort_keys=sort_keys, + **kw).encode(obj) -_default_decoder = JSONDecoder(encoding=None, object_hook=None, - object_pairs_hook=None) +_default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None) -def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, +def load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. - If the contents of ``fp`` is encoded with an ASCII based encoding other - than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must - be specified. Encodings that are not ASCII based (such as UCS-2) are - not allowed, and should be wrapped with - ``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode`` - object and passed to ``loads()`` - ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature @@ -284,22 +269,16 @@ def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, """ return loads(fp.read(), - encoding=encoding, cls=cls, object_hook=object_hook, + cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, - parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, - **kw) + parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): - """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON + """Deserialize ``s`` (a ``str`` instance containing a JSON document) to a Python object. - If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding - other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name - must be specified. Encodings that are not ASCII based (such as UCS-2) - are not allowed and should be decoded to ``unicode`` first. - ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature @@ -331,8 +310,10 @@ def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used. + The ``encoding`` argument is ignored and deprecated. + """ - if (cls is None and encoding is None and object_hook is None and + if (cls is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not kw): return _default_decoder.decode(s) @@ -348,4 +329,4 @@ def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant - return cls(encoding=encoding, **kw).decode(s) + return cls(**kw).decode(s) |
