Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Doc/library/json.rst

    r2 r391  
    88.. versionadded:: 2.6
    99
    10 JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript
    11 syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.
     10`JSON (JavaScript Object Notation) <http://json.org>`_, specified by
     11:rfc:`4627`, is a lightweight data interchange format based on a subset of
     12`JavaScript <http://en.wikipedia.org/wiki/JavaScript>`_ syntax (`ECMA-262 3rd
     13edition <http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf>`_).
    1214
    1315:mod:`json` exposes an API familiar to users of the standard library
     
    4244
    4345    >>> import json
    44     >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
     46    >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
     47    ...                  indent=4, separators=(',', ': '))
    4548    {
    4649        "4": 5,
     
    8285    ...         if isinstance(obj, complex):
    8386    ...             return [obj.real, obj.imag]
     87    ...         # Let the base class default method raise the TypeError
    8488    ...         return json.JSONEncoder.default(self, obj)
    8589    ...
     
    100104        "json": "obj"
    101105    }
    102     $ echo '{ 1.2:3.4}' | python -mjson.tool
    103     Expecting property name: line 1 column 2 (char 2)
     106    $ echo '{1.2:3.4}' | python -mjson.tool
     107    Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
    104108
    105109.. highlight:: python
     
    107111.. note::
    108112
    109    The JSON produced by this module's default settings is a subset of
    110    YAML, so it may be used as a serializer for that as well.
     113   JSON is a subset of `YAML <http://yaml.org/>`_ 1.2.  The JSON produced by
     114   this module's default settings (in particular, the default *separators*
     115   value) is also a subset of YAML 1.0 and 1.1.  This module can thus also be
     116   used as a YAML serializer.
    111117
    112118
     
    114120-----------
    115121
    116 .. function:: dump(obj, fp[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]])
     122.. function:: dump(obj, fp, skipkeys=False, ensure_ascii=True, \
     123                   check_circular=True, allow_nan=True, cls=None, \
     124                   indent=None, separators=None, encoding="utf-8", \
     125                   default=None, sort_keys=False, **kw)
    117126
    118127   Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
    119    file-like object).
     128   :term:`file-like object`) using this :ref:`conversion table
     129   <py-to-json-table>`.
    120130
    121131   If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
     
    124134   :exc:`TypeError`.
    125135
    126    If *ensure_ascii* is ``False`` (default: ``True``), then some chunks written
    127    to *fp* may be :class:`unicode` instances, subject to normal Python
    128    :class:`str` to :class:`unicode` coercion rules.  Unless ``fp.write()``
    129    explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`) this
    130    is likely to cause an error.
     136   If *ensure_ascii* is ``True`` (the default), all non-ASCII characters in the
     137   output are escaped with ``\uXXXX`` sequences, and the result is a
     138   :class:`str` instance consisting of ASCII characters only.  If
     139   *ensure_ascii* is ``False``, some chunks written to *fp* may be
     140   :class:`unicode` instances.  This usually happens because the input contains
     141   unicode strings or the *encoding* parameter is used.  Unless ``fp.write()``
     142   explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`)
     143   this is likely to cause an error.
    131144
    132145   If *check_circular* is ``False`` (default: ``True``), then the circular
     
    140153
    141154   If *indent* is a non-negative integer, then JSON array elements and object
    142    members will be pretty-printed with that indent level.  An indent level of 0
    143    will only insert newlines.  ``None`` (the default) selects the most compact
    144    representation.
     155   members will be pretty-printed with that indent level.  An indent level of 0,
     156   or negative, will only insert newlines.  ``None`` (the default) selects the
     157   most compact representation.
     158
     159   .. note::
     160
     161      Since the default item separator is ``', '``,  the output might include
     162      trailing whitespace when *indent* is specified.  You can use
     163      ``separators=(',', ': ')`` to avoid this.
    145164
    146165   If *separators* is an ``(item_separator, dict_separator)`` tuple, then it
     
    153172   *obj* or raise :exc:`TypeError`.  The default simply raises :exc:`TypeError`.
    154173
     174   If *sort_keys* is ``True`` (default: ``False``), then the output of
     175   dictionaries will be sorted by key.
     176
    155177   To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
    156178   :meth:`default` method to serialize additional types), specify it with the
    157    *cls* kwarg.
    158 
    159 
    160 .. function:: dumps(obj[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]])
    161 
    162    Serialize *obj* to a JSON formatted :class:`str`.
    163 
    164    If *ensure_ascii* is ``False``, then the return value will be a
    165    :class:`unicode` instance.  The other arguments have the same meaning as in
    166    :func:`dump`.
    167 
    168 
    169 .. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]])
    170 
    171    Deserialize *fp* (a ``.read()``-supporting file-like object containing a JSON
    172    document) to a Python object.
     179   *cls* kwarg; otherwise :class:`JSONEncoder` is used.
     180
     181   .. note::
     182
     183      Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol so
     184      trying to serialize more objects with repeated calls to :func:`dump` and
     185      the same *fp* will result in an invalid JSON file.
     186
     187.. function:: dumps(obj, skipkeys=False, ensure_ascii=True, \
     188                    check_circular=True, allow_nan=True, cls=None, \
     189                    indent=None, separators=None, encoding="utf-8", \
     190                    default=None, sort_keys=False, **kw)
     191
     192   Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion
     193   table <py-to-json-table>`.  If *ensure_ascii* is ``False``, the result may
     194   contain non-ASCII characters and the return value may be a :class:`unicode`
     195   instance.
     196
     197   The arguments have the same meaning as in :func:`dump`.
     198
     199   .. note::
     200
     201      Keys in key/value pairs of JSON are always of the type :class:`str`. When
     202      a dictionary is converted into JSON, all the keys of the dictionary are
     203      coerced to strings. As a result of this, if a dictionary is converted
     204      into JSON and then back into a dictionary, the dictionary may not equal
     205      the original one. That is, ``loads(dumps(x)) != x`` if x has non-string
     206      keys.
     207
     208.. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
     209
     210   Deserialize *fp* (a ``.read()``-supporting :term:`file-like object`
     211   containing a JSON document) to a Python object using this :ref:`conversion
     212   table <json-to-py-table>`.
    173213
    174214   If the contents of *fp* are encoded with an ASCII based encoding other than
     
    181221   any object literal decoded (a :class:`dict`).  The return value of
    182222   *object_hook* will be used instead of the :class:`dict`.  This feature can be used
    183    to implement custom decoders (e.g. JSON-RPC class hinting).
     223   to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_
     224   class hinting).
     225
     226   *object_pairs_hook* is an optional function that will be called with the
     227   result of any object literal decoded with an ordered list of pairs.  The
     228   return value of *object_pairs_hook* will be used instead of the
     229   :class:`dict`.  This feature can be used to implement custom decoders that
     230   rely on the order that the key and value pairs are decoded (for example,
     231   :func:`collections.OrderedDict` will remember the order of insertion). If
     232   *object_hook* is also defined, the *object_pairs_hook* takes priority.
     233
     234   .. versionchanged:: 2.7
     235      Added support for *object_pairs_hook*.
    184236
    185237   *parse_float*, if specified, will be called with the string of every JSON
     
    194246
    195247   *parse_constant*, if specified, will be called with one of the following
    196    strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
    197    ``'false'``.  This can be used to raise an exception if invalid JSON numbers
     248   strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
     249   This can be used to raise an exception if invalid JSON numbers
    198250   are encountered.
    199251
     252   .. versionchanged:: 2.7
     253      *parse_constant* doesn't get called on 'null', 'true', 'false' anymore.
     254
    200255   To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
    201    kwarg.  Additional keyword arguments will be passed to the constructor of the
    202    class.
    203 
    204 
    205 .. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, **kw]]]]]]])
     256   kwarg; otherwise :class:`JSONDecoder` is used.  Additional keyword arguments
     257   will be passed to the constructor of the class.
     258
     259
     260.. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
    206261
    207262   Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON
    208    document) to a Python object.
     263   document) to a Python object using this :ref:`conversion table
     264   <json-to-py-table>`.
    209265
    210266   If *s* is a :class:`str` instance and is encoded with an ASCII based encoding
     
    213269   allowed and should be decoded to :class:`unicode` first.
    214270
    215    The other arguments have the same meaning as in :func:`dump`.
    216 
    217 
    218 Encoders and decoders
     271   The other arguments have the same meaning as in :func:`load`.
     272
     273
     274Encoders and Decoders
    219275---------------------
    220276
    221 .. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict]]]]]])
     277.. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]])
    222278
    223279   Simple JSON decoder.
    224280
    225281   Performs the following translations in decoding by default:
     282
     283   .. _json-to-py-table:
    226284
    227285   +---------------+-------------------+
     
    260318   support JSON-RPC class hinting).
    261319
     320   *object_pairs_hook*, if specified will be called with the result of every
     321   JSON object decoded with an ordered list of pairs.  The return value of
     322   *object_pairs_hook* will be used instead of the :class:`dict`.  This
     323   feature can be used to implement custom decoders that rely on the order
     324   that the key and value pairs are decoded (for example,
     325   :func:`collections.OrderedDict` will remember the order of insertion). If
     326   *object_hook* is also defined, the *object_pairs_hook* takes priority.
     327
     328   .. versionchanged:: 2.7
     329      Added support for *object_pairs_hook*.
     330
    262331   *parse_float*, if specified, will be called with the string of every JSON
    263332   float to be decoded.  By default, this is equivalent to ``float(num_str)``.
     
    275344   are encountered.
    276345
     346   If *strict* is ``False`` (``True`` is the default), then control characters
     347   will be allowed inside strings.  Control characters in this context are
     348   those with character codes in the 0-31 range, including ``'\t'`` (tab),
     349   ``'\n'``, ``'\r'`` and ``'\0'``.
     350
     351   If the data being deserialized is not a valid JSON document, a
     352   :exc:`ValueError` will be raised.
    277353
    278354   .. method:: decode(s)
     
    296372
    297373   Supports the following objects and types by default:
     374
     375   .. _py-to-json-table:
    298376
    299377   +-------------------+---------------+
     
    324402   *skipkeys* is ``True``, such items are simply skipped.
    325403
    326    If *ensure_ascii* is ``True`` (the default), the output is guaranteed to be
    327    :class:`str` objects with all incoming unicode characters escaped.  If
    328    *ensure_ascii* is ``False``, the output will be a unicode object.
     404   If *ensure_ascii* is ``True`` (the default), all non-ASCII characters in the
     405   output are escaped with ``\uXXXX`` sequences, and the results are
     406   :class:`str` instances consisting of ASCII characters only. If
     407   *ensure_ascii* is ``False``, a result may be a :class:`unicode`
     408   instance. This usually happens if the input contains unicode strings or the
     409   *encoding* parameter is used.
    329410
    330411   If *check_circular* is ``True`` (the default), then lists, dicts, and custom
     
    339420   such floats.
    340421
    341    If *sort_keys* is ``True`` (the default), then the output of dictionaries
     422   If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
    342423   will be sorted by key; this is useful for regression tests to ensure that
    343424   JSON serializations can be compared on a day-to-day basis.
     
    347428   level.  An indent level of 0 will only insert newlines.  ``None`` is the most
    348429   compact representation.
     430
     431   .. note::
     432
     433      Since the default item separator is ``', '``,  the output might include
     434      trailing whitespace when *indent* is specified.  You can use
     435      ``separators=(',', ': ')`` to avoid this.
    349436
    350437   If specified, *separators* should be an ``(item_separator, key_separator)``
     
    377464            else:
    378465                return list(iterable)
     466            # Let the base class default method raise the TypeError
    379467            return JSONEncoder.default(self, o)
    380468
     
    396484            for chunk in JSONEncoder().iterencode(bigobject):
    397485                mysocket.write(chunk)
     486
     487
     488Standard Compliance
     489-------------------
     490
     491The JSON format is specified by :rfc:`4627`.  This section details this
     492module's level of compliance with the RFC.  For simplicity,
     493:class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and parameters other
     494than those explicitly mentioned, are not considered.
     495
     496This module does not comply with the RFC in a strict fashion, implementing some
     497extensions that are valid JavaScript but not valid JSON.  In particular:
     498
     499- Top-level non-object, non-array values are accepted and output;
     500- Infinite and NaN number values are accepted and output;
     501- Repeated names within an object are accepted, and only the value of the last
     502  name-value pair is used.
     503
     504Since the RFC permits RFC-compliant parsers to accept input texts that are not
     505RFC-compliant, this module's deserializer is technically RFC-compliant under
     506default settings.
     507
     508Character Encodings
     509^^^^^^^^^^^^^^^^^^^
     510
     511The RFC recommends that JSON be represented using either UTF-8, UTF-16, or
     512UTF-32, with UTF-8 being the default.  Accordingly, this module uses UTF-8 as
     513the default for its *encoding* parameter.
     514
     515This module's deserializer only directly works with ASCII-compatible encodings;
     516UTF-16, UTF-32, and other ASCII-incompatible encodings require the use of
     517workarounds described in the documentation for the deserializer's *encoding*
     518parameter.
     519
     520The RFC also non-normatively describes a limited encoding detection technique
     521for JSON texts; this module's deserializer does not implement this or any other
     522kind of encoding detection.
     523
     524As permitted, though not required, by the RFC, this module's serializer sets
     525*ensure_ascii=True* by default, thus escaping the output so that the resulting
     526strings only contain ASCII characters.
     527
     528
     529Top-level Non-Object, Non-Array Values
     530^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     531
     532The RFC specifies that the top-level value of a JSON text must be either a
     533JSON object or array (Python :class:`dict` or :class:`list`).  This module's
     534deserializer also accepts input texts consisting solely of a
     535JSON null, boolean, number, or string value::
     536
     537   >>> just_a_json_string = '"spam and eggs"'  # Not by itself a valid JSON text
     538   >>> json.loads(just_a_json_string)
     539   u'spam and eggs'
     540
     541This module itself does not include a way to request that such input texts be
     542regarded as illegal.  Likewise, this module's serializer also accepts single
     543Python :data:`None`, :class:`bool`, numeric, and :class:`str`
     544values as input and will generate output texts consisting solely of a top-level
     545JSON null, boolean, number, or string value without raising an exception::
     546
     547   >>> neither_a_list_nor_a_dict = u"spam and eggs"
     548   >>> json.dumps(neither_a_list_nor_a_dict)  # The result is not a valid JSON text
     549   '"spam and eggs"'
     550
     551This module's serializer does not itself include a way to enforce the
     552aforementioned constraint.
     553
     554
     555Infinite and NaN Number Values
     556^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     557
     558The RFC does not permit the representation of infinite or NaN number values.
     559Despite that, by default, this module accepts and outputs ``Infinity``,
     560``-Infinity``, and ``NaN`` as if they were valid JSON number literal values::
     561
     562   >>> # Neither of these calls raises an exception, but the results are not valid JSON
     563   >>> json.dumps(float('-inf'))
     564   '-Infinity'
     565   >>> json.dumps(float('nan'))
     566   'NaN'
     567   >>> # Same when deserializing
     568   >>> json.loads('-Infinity')
     569   -inf
     570   >>> json.loads('NaN')
     571   nan
     572
     573In the serializer, the *allow_nan* parameter can be used to alter this
     574behavior.  In the deserializer, the *parse_constant* parameter can be used to
     575alter this behavior.
     576
     577
     578Repeated Names Within an Object
     579^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     580
     581The RFC specifies that the names within a JSON object should be unique, but
     582does not specify how repeated names in JSON objects should be handled.  By
     583default, this module does not raise an exception; instead, it ignores all but
     584the last name-value pair for a given name::
     585
     586   >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
     587   >>> json.loads(weird_json)
     588   {u'x': 3}
     589
     590The *object_pairs_hook* parameter can be used to alter this behavior.
Note: See TracChangeset for help on using the changeset viewer.