18.2. json — JSON 编码和解码器

2.6 新版功能.

JSON (JavaScript Object Notation),由 RFC 7159 (which obsoletes RFC 4627) 和 ECMA-404 指定,是一个受 JavaScript 的对象字面量语法启发的轻量级数据交换格式,尽管它不仅仅是一个严格意义上的 JavaScript 的字集 1

json 提供了与标准库 marshalpickle 相似的API接口。

对基本的 Python 对象层次结构进行编码:

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print json.dumps("\"foo\bar")
"\"foo\bar"
>>> print json.dumps(u'\u1234')
"\u1234"
>>> print json.dumps('\\')
"\\"
>>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'

紧凑编码:

>>> import json
>>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
'[1,2,3,{"4":5,"6":7}]'

美化输出:

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
...                  indent=4, separators=(',', ': '))
{
    "4": 5,
    "6": 7
}

JSON解码:

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> json.loads('"\\"foo\\bar"')
u'"foo\x08ar'
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)
[u'streaming API']

特殊 JSON 对象解码:

>>> import json
>>> def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
...     object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1')

扩展 JSONEncoder

>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[', '2.0', ', ', '1.0', ']']

Using json.tool from the shell to validate and pretty-print:

$ echo '{"json":"obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -mjson.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

注解

JSON 是 YAML 1.2 的一个子集。由该模块的默认设置生成的 JSON (尤其是默认的 “分隔符” 设置值)也是 YAML 1.0 and 1.1 的一个子集。因此该模块也能够用于序列化为 YAML。

18.2.1. 基本使用

json.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)

使用这个 转换表obj 序列化为 JSON 格式化流形式的 fp (支持 .write()file-like object)。

If skipkeys is true (default: False), then dict keys that are not of a basic type (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.

如果 check_circular 是为假值 (默认为 True),那么容器类型的循环引用检验会被跳过并且循环引用会引发一个 OverflowError (或者更糟的情况)。

如果 allow_nan 是 false(默认为 True),那么在对严格 JSON 规格范围外的 float 类型值(naninf-inf)进行序列化时会引发一个 ValueError。如果 allow_nan 是 true,则使用它们的 JavaScript 等价形式(NaNInfinity-Infinity)。

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. None (the default) selects the most compact representation.

注解

Since the default item separator is ', ', the output might include trailing whitespace when indent is specified. You can use separators=(',', ': ') to avoid this.

If specified, separators should be an (item_separator, key_separator) tuple. By default, (', ', ': ') are used. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

encoding is the character encoding for str instances, default is UTF-8.

default 被指定时,其应该是一个函数,每当某个对象无法被序列化时它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一个 TypeError。如果没有被指定,则会直接引发 TypeError

如果 sort_keys 是 true(默认为 False),那么字典的输出会以键的顺序排序。

为了使用一个自定义的 JSONEncoder 子类(比如:覆盖了 default() 方法来序列化额外的类型), 通过 cls 关键字参数来指定;否则将使用 JSONEncoder

注解

Unlike pickle and marshal, JSON is not a framed protocol so trying to serialize more objects with repeated calls to dump() and the same fp will result in an invalid JSON file.

json.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)

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is false, the result may contain non-ASCII characters and the return value may be a unicode instance.

The arguments have the same meaning as in dump().

注解

JSON 中的键-值对中的键永远是 str 类型的。当一个对象被转化为 JSON 时,字典中所有的键都会被强制转换为字符串。这所造成的结果是字典被转换为 JSON 然后转换回字典时可能和原来的不相等。换句话说,如果 x 具有非字符串的键,则有 loads(dumps(x)) != x

json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

If the contents of fp are 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(encoding)(fp), or simply decoded to a unicode object and passed to loads().

object_hook 是一个可选的函数,它会被调用于每一个解码出的对象字面量(即一个 dict)。object_hook 的返回值会取代原本的 dict。这一特性能够被用于实现自定义解码器(如 JSON-RPC 的类型提示)。

object_pairs_hook is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

在 2.7 版更改: 添加了对 object_pairs_hook 的支持。

parse_float ,如果指定,将与每个要解码 JSON 浮点数一同调用。默认状态下,相当于 float(num_str) 。可以用于对 JSON 浮点数使用其它数据类型和解析器 (比如 decimal.Decimal )。

parse_int ,如果指定,将与每个要解码 JSON 整数的字符串一同调用。默认状态下,相当于 int(num_str) 。可以用于对 JSON 整数使用其它数据类型和语法分析程序 (比如 float )。

parse_constant ,如果指定,将要与以下字符串中的一个一同调用: '-Infinity''Infinity''NaN' 。如果遇到无效的 JSON 数字它会被用于抛出异常。

在 2.7 版更改: parse_constant 不再调用 ‘null’ , ‘true’ , ‘false’ 。

要使用自定义的 JSONDecoder 子类,用 cls 指定他;否则使用 JSONDecoder 。额外的关键词参数会通过类的构造函数传递。

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.

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.

The other arguments have the same meaning as in load().

18.2.2. 编码器和解码器

class json.JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]])

简单的JSON解码器。

默认情况下,解码执行以下翻译:

JSON

Python

object

dict

array

list

string

unicode

number (int)

int, long

number (real)

float

true

True

false

False

null

None

它还将“NaN”、“Infinity”和“-Infinity”理解为它们对应的“float”值,这超出了JSON规范。

encoding determines the encoding used to interpret any str objects decoded by this instance (UTF-8 by default). It has no effect when decoding unicode objects.

Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as unicode.

object_hook ,如果指定,会被每个解码的 JSON 对象的结果调用,并且返回值会替代给定 dict 。它可被用于提供自定义反序列化(比如去支持 JSON-RPC 类的暗示)。

object_pairs_hook, if specified will be called with the result of every JSON object decoded with an ordered list of pairs. The return value of object_pairs_hook will be used instead of the dict. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict() will remember the order of insertion). If object_hook is also defined, the object_pairs_hook takes priority.

在 2.7 版更改: 添加了对 object_pairs_hook 的支持。

parse_float ,如果指定,将与每个要解码 JSON 浮点数一同调用。默认状态下,相当于 float(num_str) 。可以用于对 JSON 浮点数使用其它数据类型和解析器 (比如 decimal.Decimal )。

parse_int ,如果指定,将与每个要解码 JSON 整数的字符串一同调用。默认状态下,相当于 int(num_str) 。可以用于对 JSON 整数使用其它数据类型和语法分析程序 (比如 float )。

parse_constant ,如果指定,将要与以下字符串中的一个一同调用: '-Infinity''Infinity''NaN' 。如果遇到无效的 JSON 数字它会被用于抛出异常。

如果 strict 为 false (默认为 True ),那么控制字符将被允许在字符串内。在此上下文中的控制字符是那些编码于范围 0 – 31 的字符,包括 '\t' (制表符), '\n''\0'

If the data being deserialized is not a valid JSON document, a ValueError will be raised.

decode(s)

Return the Python representation of s (a str or unicode instance containing a JSON document).

raw_decode(s)

Decode a JSON document from s (a str or unicode beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended.

这可以用于从一个字符串解码JSON文档,该字符串的末尾可能有无关的数据。

class json.JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default]]]]]]]]])

用于Python数据结构的可扩展JSON编码器。

默认支持以下对象和类型:

Python

JSON

dict

object

list, tuple

array

str, unicode

string

int, long, float

number

True

true

False

false

None

null

为了将其拓展至识别其他对象,需要子类化并实现 default() 方法于另一种返回 o 的可序列化对象的方法如果可行,否则它应该调用超类实现(来引发 TypeError )。

If skipkeys is false (the default), then it is a TypeError to attempt encoding of keys that are not str, int, long, float or None. If skipkeys is true, such items are simply skipped.

If ensure_ascii is true (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences, and the results are str instances consisting of ASCII characters only. If ensure_ascii is false, a result may be a unicode instance. This usually happens if the input contains unicode strings or the encoding parameter is used.

如果 check_circular 为 true (默认),那么列表,字典,和自定义编码的对象在编码期间会被检查重复循环引用防止无限递归(无限递归将导致 OverflowError )。否则,这样进行检查。

如果 allow_nan 为 true (默认),那么 NaNInfinity ,和 -Infinity 进行编码。此行为不符合 JSON 规范,但与大多数的基于 Javascript 的编码器和解码器一致。否则,它将是一个 ValueError 来编码这些浮点数。

如果 sort_keys 为 true (默认为: False ),那么字典的输出是按照键排序;这对回归测试很有用,以确保可以每天比较 JSON 序列化。

If indent is a non-negative integer (it is None by default), then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

注解

Since the default item separator is ', ', the output might include trailing whitespace when indent is specified. You can use separators=(',', ': ') to avoid this.

If specified, separators should be an (item_separator, key_separator) tuple. By default, (', ', ': ') are used. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

default 被指定时,其应该是一个函数,每当某个对象无法被序列化时它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一个 TypeError。如果没有被指定,则会直接引发 TypeError

If encoding is not None, then all input strings will be transformed into unicode using that encoding prior to JSON-encoding. The default is UTF-8.

default(o)

在子类中实现这种方法使其返回 o 的可序列化对象,或者调用基础实现(引发 TypeError

比如说,为了支持任意迭代器,你可以像这样实现默认设置:

def default(self, o):
   try:
       iterable = iter(o)
   except TypeError:
       pass
   else:
       return list(iterable)
   # Let the base class default method raise the TypeError
   return JSONEncoder.default(self, o)
encode(o)

返回 Python o 数据结构的 JSON 字符串表达方式。比如说:

>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
iterencode(o)

编码给定对象 o ,并且让每个可用的字符串表达方式。例如:

for chunk in JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)

18.2.3. 标准符合性和互操作性

JSON 格式由 RFC 7159ECMA-404 指定。此段落详细讲了这个模块符合 RFC 的级别。简单来说, JSONEncoderJSONDecoder 子类,和明确提到的参数以外的参数,不作考虑。

此模块不严格遵循于 RFC ,它实现了一些扩展是有效的 Javascript 但不是有效的 JSON。尤其是:

  • 无限和 NaN 数值是可接受的并输出;

  • 对象内的重复名称是接受的,并且仅使用最后一对名称-值对。

自从 RFC 允许符合 RFC 的语法分析程序接收 不符合 RFC 的输入文本以来,这个模块的解串器在默认状态下默认符合 RFC 。

18.2.3.1. 字符编码

The RFC requires that JSON be represented using either UTF-8, UTF-16, or UTF-32, with UTF-8 being the recommended default for maximum interoperability. Accordingly, this module uses UTF-8 as the default for its encoding parameter.

This module’s deserializer only directly works with ASCII-compatible encodings; UTF-16, UTF-32, and other ASCII-incompatible encodings require the use of workarounds described in the documentation for the deserializer’s encoding parameter.

RFC允许,尽管不是必须的,这个模块的序列化默认设置为 ensure_ascii=True ,这样消除输出以便结果字符串至容纳 ASCII 字符。

RFC 禁止添加字符顺序标记( BOM )在 JSON 文本的开头,这个模块的序列化器不添加 BOM 标记在它的输出上。 RFC,准许 JSON 反序列化器忽略它们输入中的初始 BOM 标记,但不要求。此模块的反序列化器引发 ValueError 当出现初始 BOM 标记。

RFC 不会明确禁止包含字节序列的 JSON 字符串这不对应有效的 Unicode 字符(比如 不成对的 UTF-16 的替代物),但是它确实指出它们可能会导致互操作性问题。默认下,模块对这样的序列接受和输出(当在原始 str 存在时)代码点。

18.2.3.2. Infinite 和 NaN 数值。

RFC 不允许 infinite 或者 NaN 数值的表达方式。尽管这样,默认情况下,此模块接受并且输出 Infinity-Infinity,和 NaN 好像它们是有效的JSON数字字面值

>>> # Neither of these calls raises an exception, but the results are not valid JSON
>>> json.dumps(float('-inf'))
'-Infinity'
>>> json.dumps(float('nan'))
'NaN'
>>> # Same when deserializing
>>> json.loads('-Infinity')
-inf
>>> json.loads('NaN')
nan

序列化器中, allow_nan 参数可用于替代这个行为。反序列化器中, parse_constant 参数,可用于替代这个行为。

18.2.3.3. 对象中的重复名称

RFC 具体说明了 在 JSON对象里的名字应该是唯一的,但没有规定如何处理JSON对象中的重复名称。默认下,此模块不引发异常;作为替代,对于给定名它将忽略除姓-值对之外的所有对:

>>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> json.loads(weird_json)
{u'x': 3}

The object_pairs_hook parameter can be used to alter this behavior.

18.2.3.4. 顶级非对象,非数组值

过时的 RFC 4627 指定的旧版本 JSON 要求 JSON 文本顶级值必须是 JSON 对象或数组( Python dictlist ),并且不能是 JSON null 值,布尔值,数值或者字符串值。 RFC 7159 移除这个限制,此模块没有并且从未在序列化器和反序列化器中实现这个限制。

无论如何,为了最大化地获取互操作性,你可能希望自己遵守该原则。

18.2.3.5. 实现限制

一些 JSON 反序列化器的实现应该在以下方面做出限制:

  • 接受的 JSON 文本大小

  • 嵌套 JSON 对象和数组的最高水平

  • JSON 数字的范围和精度

  • JSON 字符串的内容和最大长度

此模块不强制执行任何上述限制,除了相关的 Python 数据类型本身或者 Python 解释器本身的限制以外。

当序列化为 JSON ,在应用中当心此类限制这可能破坏你的 JSON 。特别是,通常将 JSON 数字反序列化为 IEEE 754 双精度数字,从而受到该表示形式的范围和精度限制。这是特别相关的,当序列化非常大的 Python int 值时,或者当序列化 “exotic” 数值类型的实例时比如 decimal.Decimal

备注

1

正如 RFC 7159 的勘误表 所说明的,JSON 允许以字符串表示字面值字符 U+2028 (LINE SEPARATOR) 和 U+2029 (PARAGRAPH SEPARATOR),而 JavaScript (在 ECMAScript 5.1 版中) 不允许。