|
| 1 | +r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of |
| 2 | +JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data |
| 3 | +interchange format. |
| 4 | +
|
| 5 | +:mod:`json` exposes an API familiar to users of the standard library |
| 6 | +:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained |
| 7 | +version of the :mod:`json` library contained in Python 2.6, but maintains |
| 8 | +compatibility with Python 2.4 and Python 2.5 and (currently) has |
| 9 | +significant performance advantages, even without using the optional C |
| 10 | +extension for speedups. |
| 11 | +
|
| 12 | +Encoding basic Python object hierarchies:: |
| 13 | +
|
| 14 | + >>> import json |
| 15 | + >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) |
| 16 | + '["foo", {"bar": ["baz", null, 1.0, 2]}]' |
| 17 | + >>> print(json.dumps("\"foo\bar")) |
| 18 | + "\"foo\bar" |
| 19 | + >>> print(json.dumps('\u1234')) |
| 20 | + "\u1234" |
| 21 | + >>> print(json.dumps('\\')) |
| 22 | + "\\" |
| 23 | + >>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)) |
| 24 | + {"a": 0, "b": 0, "c": 0} |
| 25 | + >>> from io import StringIO |
| 26 | + >>> io = StringIO() |
| 27 | + >>> json.dump(['streaming API'], io) |
| 28 | + >>> io.getvalue() |
| 29 | + '["streaming API"]' |
| 30 | +
|
| 31 | +Compact encoding:: |
| 32 | +
|
| 33 | + >>> import json |
| 34 | + >>> from collections import OrderedDict |
| 35 | + >>> mydict = OrderedDict([('4', 5), ('6', 7)]) |
| 36 | + >>> json.dumps([1,2,3,mydict], separators=(',', ':')) |
| 37 | + '[1,2,3,{"4":5,"6":7}]' |
| 38 | +
|
| 39 | +Pretty printing:: |
| 40 | +
|
| 41 | + >>> import json |
| 42 | + >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, |
| 43 | + ... indent=4, separators=(',', ': '))) |
| 44 | + { |
| 45 | + "4": 5, |
| 46 | + "6": 7 |
| 47 | + } |
| 48 | +
|
| 49 | +Decoding JSON:: |
| 50 | +
|
| 51 | + >>> import json |
| 52 | + >>> obj = ['foo', {'bar': ['baz', None, 1.0, 2]}] |
| 53 | + >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj |
| 54 | + True |
| 55 | + >>> json.loads('"\\"foo\\bar"') == '"foo\x08ar' |
| 56 | + True |
| 57 | + >>> from io import StringIO |
| 58 | + >>> io = StringIO('["streaming API"]') |
| 59 | + >>> json.load(io)[0] == 'streaming API' |
| 60 | + True |
| 61 | +
|
| 62 | +Specializing JSON object decoding:: |
| 63 | +
|
| 64 | + >>> import json |
| 65 | + >>> def as_complex(dct): |
| 66 | + ... if '__complex__' in dct: |
| 67 | + ... return complex(dct['real'], dct['imag']) |
| 68 | + ... return dct |
| 69 | + ... |
| 70 | + >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', |
| 71 | + ... object_hook=as_complex) |
| 72 | + (1+2j) |
| 73 | + >>> from decimal import Decimal |
| 74 | + >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1') |
| 75 | + True |
| 76 | +
|
| 77 | +Specializing JSON object encoding:: |
| 78 | +
|
| 79 | + >>> import json |
| 80 | + >>> def encode_complex(obj): |
| 81 | + ... if isinstance(obj, complex): |
| 82 | + ... return [obj.real, obj.imag] |
| 83 | + ... raise TypeError(repr(o) + " is not JSON serializable") |
| 84 | + ... |
| 85 | + >>> json.dumps(2 + 1j, default=encode_complex) |
| 86 | + '[2.0, 1.0]' |
| 87 | + >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) |
| 88 | + '[2.0, 1.0]' |
| 89 | + >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) |
| 90 | + '[2.0, 1.0]' |
| 91 | +
|
| 92 | +
|
| 93 | +Using json.tool from the shell to validate and pretty-print:: |
| 94 | +
|
| 95 | + $ echo '{"json":"obj"}' | python -m json.tool |
| 96 | + { |
| 97 | + "json": "obj" |
| 98 | + } |
| 99 | + $ echo '{ 1.2:3.4}' | python -m json.tool |
| 100 | + Expecting property name enclosed in double quotes: line 1 column 3 (char 2) |
| 101 | +""" |
| 102 | +__version__ = '2.0.9' |
| 103 | +__all__ = [ |
| 104 | + 'dump', 'dumps', 'load', 'loads', |
| 105 | + 'JSONDecoder', 'JSONEncoder', |
| 106 | +] |
| 107 | + |
| 108 | +__author__ = 'Bob Ippolito <[email protected]>' |
| 109 | + |
| 110 | +from .decoder import JSONDecoder |
| 111 | +from .encoder import JSONEncoder |
| 112 | + |
| 113 | +_default_encoder = JSONEncoder( |
| 114 | + skipkeys=False, |
| 115 | + ensure_ascii=True, |
| 116 | + check_circular=True, |
| 117 | + allow_nan=True, |
| 118 | + indent=None, |
| 119 | + separators=None, |
| 120 | + default=None, |
| 121 | +) |
| 122 | + |
| 123 | +def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, |
| 124 | + allow_nan=True, cls=None, indent=None, separators=None, |
| 125 | + default=None, sort_keys=False, **kw): |
| 126 | + """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a |
| 127 | + ``.write()``-supporting file-like object). |
| 128 | +
|
| 129 | + If ``skipkeys`` is true then ``dict`` keys that are not basic types |
| 130 | + (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped |
| 131 | + instead of raising a ``TypeError``. |
| 132 | +
|
| 133 | + If ``ensure_ascii`` is false, then the strings written to ``fp`` can |
| 134 | + contain non-ASCII characters if they appear in strings contained in |
| 135 | + ``obj``. Otherwise, all such characters are escaped in JSON strings. |
| 136 | +
|
| 137 | + If ``check_circular`` is false, then the circular reference check |
| 138 | + for container types will be skipped and a circular reference will |
| 139 | + result in an ``OverflowError`` (or worse). |
| 140 | +
|
| 141 | + If ``allow_nan`` is false, then it will be a ``ValueError`` to |
| 142 | + serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) |
| 143 | + in strict compliance of the JSON specification, instead of using the |
| 144 | + JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). |
| 145 | +
|
| 146 | + If ``indent`` is a non-negative integer, then JSON array elements and |
| 147 | + object members will be pretty-printed with that indent level. An indent |
| 148 | + level of 0 will only insert newlines. ``None`` is the most compact |
| 149 | + representation. Since the default item separator is ``', '``, the |
| 150 | + output might include trailing whitespace when ``indent`` is specified. |
| 151 | + You can use ``separators=(',', ': ')`` to avoid this. |
| 152 | +
|
| 153 | + If ``separators`` is an ``(item_separator, dict_separator)`` tuple |
| 154 | + then it will be used instead of the default ``(', ', ': ')`` separators. |
| 155 | + ``(',', ':')`` is the most compact JSON representation. |
| 156 | +
|
| 157 | + ``default(obj)`` is a function that should return a serializable version |
| 158 | + of obj or raise TypeError. The default simply raises TypeError. |
| 159 | +
|
| 160 | + If *sort_keys* is ``True`` (default: ``False``), then the output of |
| 161 | + dictionaries will be sorted by key. |
| 162 | +
|
| 163 | + To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the |
| 164 | + ``.default()`` method to serialize additional types), specify it with |
| 165 | + the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. |
| 166 | +
|
| 167 | + """ |
| 168 | + # cached encoder |
| 169 | + if (not skipkeys and ensure_ascii and |
| 170 | + check_circular and allow_nan and |
| 171 | + cls is None and indent is None and separators is None and |
| 172 | + default is None and not sort_keys and not kw): |
| 173 | + iterable = _default_encoder.iterencode(obj) |
| 174 | + else: |
| 175 | + if cls is None: |
| 176 | + cls = JSONEncoder |
| 177 | + iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, |
| 178 | + check_circular=check_circular, allow_nan=allow_nan, indent=indent, |
| 179 | + separators=separators, |
| 180 | + default=default, sort_keys=sort_keys, **kw).iterencode(obj) |
| 181 | + # could accelerate with writelines in some versions of Python, at |
| 182 | + # a debuggability cost |
| 183 | + for chunk in iterable: |
| 184 | + fp.write(chunk) |
| 185 | + |
| 186 | + |
| 187 | +def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, |
| 188 | + allow_nan=True, cls=None, indent=None, separators=None, |
| 189 | + default=None, sort_keys=False, **kw): |
| 190 | + """Serialize ``obj`` to a JSON formatted ``str``. |
| 191 | +
|
| 192 | + If ``skipkeys`` is false then ``dict`` keys that are not basic types |
| 193 | + (``str``, ``int``, ``float``, ``bool``, ``None``) will be skipped |
| 194 | + instead of raising a ``TypeError``. |
| 195 | +
|
| 196 | + If ``ensure_ascii`` is false, then the return value can contain non-ASCII |
| 197 | + characters if they appear in strings contained in ``obj``. Otherwise, all |
| 198 | + such characters are escaped in JSON strings. |
| 199 | +
|
| 200 | + If ``check_circular`` is false, then the circular reference check |
| 201 | + for container types will be skipped and a circular reference will |
| 202 | + result in an ``OverflowError`` (or worse). |
| 203 | +
|
| 204 | + If ``allow_nan`` is false, then it will be a ``ValueError`` to |
| 205 | + serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in |
| 206 | + strict compliance of the JSON specification, instead of using the |
| 207 | + JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). |
| 208 | +
|
| 209 | + If ``indent`` is a non-negative integer, then JSON array elements and |
| 210 | + object members will be pretty-printed with that indent level. An indent |
| 211 | + level of 0 will only insert newlines. ``None`` is the most compact |
| 212 | + representation. Since the default item separator is ``', '``, the |
| 213 | + output might include trailing whitespace when ``indent`` is specified. |
| 214 | + You can use ``separators=(',', ': ')`` to avoid this. |
| 215 | +
|
| 216 | + If ``separators`` is an ``(item_separator, dict_separator)`` tuple |
| 217 | + then it will be used instead of the default ``(', ', ': ')`` separators. |
| 218 | + ``(',', ':')`` is the most compact JSON representation. |
| 219 | +
|
| 220 | + ``default(obj)`` is a function that should return a serializable version |
| 221 | + of obj or raise TypeError. The default simply raises TypeError. |
| 222 | +
|
| 223 | + If *sort_keys* is ``True`` (default: ``False``), then the output of |
| 224 | + dictionaries will be sorted by key. |
| 225 | +
|
| 226 | + To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the |
| 227 | + ``.default()`` method to serialize additional types), specify it with |
| 228 | + the ``cls`` kwarg; otherwise ``JSONEncoder`` is used. |
| 229 | +
|
| 230 | + """ |
| 231 | + # cached encoder |
| 232 | + if (not skipkeys and ensure_ascii and |
| 233 | + check_circular and allow_nan and |
| 234 | + cls is None and indent is None and separators is None and |
| 235 | + default is None and not sort_keys and not kw): |
| 236 | + return _default_encoder.encode(obj) |
| 237 | + if cls is None: |
| 238 | + cls = JSONEncoder |
| 239 | + return cls( |
| 240 | + skipkeys=skipkeys, ensure_ascii=ensure_ascii, |
| 241 | + check_circular=check_circular, allow_nan=allow_nan, indent=indent, |
| 242 | + separators=separators, default=default, sort_keys=sort_keys, |
| 243 | + **kw).encode(obj) |
| 244 | + |
| 245 | + |
| 246 | +_default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None) |
| 247 | + |
| 248 | + |
| 249 | +def load(fp, cls=None, object_hook=None, parse_float=None, |
| 250 | + parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): |
| 251 | + """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing |
| 252 | + a JSON document) to a Python object. |
| 253 | +
|
| 254 | + ``object_hook`` is an optional function that will be called with the |
| 255 | + result of any object literal decode (a ``dict``). The return value of |
| 256 | + ``object_hook`` will be used instead of the ``dict``. This feature |
| 257 | + can be used to implement custom decoders (e.g. JSON-RPC class hinting). |
| 258 | +
|
| 259 | + ``object_pairs_hook`` is an optional function that will be called with the |
| 260 | + result of any object literal decoded with an ordered list of pairs. The |
| 261 | + return value of ``object_pairs_hook`` will be used instead of the ``dict``. |
| 262 | + This feature can be used to implement custom decoders that rely on the |
| 263 | + order that the key and value pairs are decoded (for example, |
| 264 | + collections.OrderedDict will remember the order of insertion). If |
| 265 | + ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. |
| 266 | +
|
| 267 | + To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` |
| 268 | + kwarg; otherwise ``JSONDecoder`` is used. |
| 269 | +
|
| 270 | + """ |
| 271 | + return loads(fp.read(), |
| 272 | + cls=cls, object_hook=object_hook, |
| 273 | + parse_float=parse_float, parse_int=parse_int, |
| 274 | + parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) |
| 275 | + |
| 276 | + |
| 277 | +def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, |
| 278 | + parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): |
| 279 | + """Deserialize ``s`` (a ``str`` instance containing a JSON |
| 280 | + document) to a Python object. |
| 281 | +
|
| 282 | + ``object_hook`` is an optional function that will be called with the |
| 283 | + result of any object literal decode (a ``dict``). The return value of |
| 284 | + ``object_hook`` will be used instead of the ``dict``. This feature |
| 285 | + can be used to implement custom decoders (e.g. JSON-RPC class hinting). |
| 286 | +
|
| 287 | + ``object_pairs_hook`` is an optional function that will be called with the |
| 288 | + result of any object literal decoded with an ordered list of pairs. The |
| 289 | + return value of ``object_pairs_hook`` will be used instead of the ``dict``. |
| 290 | + This feature can be used to implement custom decoders that rely on the |
| 291 | + order that the key and value pairs are decoded (for example, |
| 292 | + collections.OrderedDict will remember the order of insertion). If |
| 293 | + ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. |
| 294 | +
|
| 295 | + ``parse_float``, if specified, will be called with the string |
| 296 | + of every JSON float to be decoded. By default this is equivalent to |
| 297 | + float(num_str). This can be used to use another datatype or parser |
| 298 | + for JSON floats (e.g. decimal.Decimal). |
| 299 | +
|
| 300 | + ``parse_int``, if specified, will be called with the string |
| 301 | + of every JSON int to be decoded. By default this is equivalent to |
| 302 | + int(num_str). This can be used to use another datatype or parser |
| 303 | + for JSON integers (e.g. float). |
| 304 | +
|
| 305 | + ``parse_constant``, if specified, will be called with one of the |
| 306 | + following strings: -Infinity, Infinity, NaN, null, true, false. |
| 307 | + This can be used to raise an exception if invalid JSON numbers |
| 308 | + are encountered. |
| 309 | +
|
| 310 | + To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` |
| 311 | + kwarg; otherwise ``JSONDecoder`` is used. |
| 312 | +
|
| 313 | + The ``encoding`` argument is ignored and deprecated. |
| 314 | +
|
| 315 | + """ |
| 316 | + if (cls is None and object_hook is None and |
| 317 | + parse_int is None and parse_float is None and |
| 318 | + parse_constant is None and object_pairs_hook is None and not kw): |
| 319 | + return _default_decoder.decode(s) |
| 320 | + if cls is None: |
| 321 | + cls = JSONDecoder |
| 322 | + if object_hook is not None: |
| 323 | + kw['object_hook'] = object_hook |
| 324 | + if object_pairs_hook is not None: |
| 325 | + kw['object_pairs_hook'] = object_pairs_hook |
| 326 | + if parse_float is not None: |
| 327 | + kw['parse_float'] = parse_float |
| 328 | + if parse_int is not None: |
| 329 | + kw['parse_int'] = parse_int |
| 330 | + if parse_constant is not None: |
| 331 | + kw['parse_constant'] = parse_constant |
| 332 | + return cls(**kw).decode(s) |
0 commit comments