json - JSON encoder and decoder - JSON 编码器和解码器

json - JSON encoder and decoder - JSON 编码器和解码器

https://docs.python.org/zh-cn/3.7/library/json.html
https://docs.python.org/3.7/library/json.html

JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict subset of JavaScript).
JSON (JavaScript Object Notation),由 RFC 7159 (which obsoletes RFC 4627) 和 ECMA-404 指定,是一个受 JavaScript 的对象字面量语法启发的轻量级数据交换格式,尽管它不仅仅是一个严格意义上的 JavaScript 的字集。

obsolete ['ɒbsəliːt]:adj. 废弃的,老式的 n. 废词,陈腐的人 vt. 淘汰,废弃

json exposes an API familiar to users of the standard library marshal and pickle modules.
json 提供了与标准库 marshal 和 pickle 相似的API接口。

Encoding basic Python object hierarchies:
对基本的 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('\u1234'))
"\u1234"
>>> print(json.dumps('\\'))
"\\"
>>> print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
>>> from io import StringIO
>>> io = StringIO()
>>> json.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'

Compact encoding (紧凑编码):

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

Pretty printing (美化输出):

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

Decoding JSON (JSON 解码):

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

Using json.tool from the shell to validate and pretty-print (从命令行使用 json.tool 来验证并美化输出):

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

1. Basic Usage

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using this conversion table.
使用这个 conversion table 来序列化 obj 为一个 JSON 格式的流并输出到 fp (一个支持 .write() 的 file-like object)。

If skipkeys is true (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.
如果 skipkeys 是 true (默认为 False),那么那些不是基本对象 (包括 str、int、float、bool、None) 的字典的键会被跳过;否则引发一个 TypeError。

The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.
json 模块始终产生 str 对象而非 bytes 对象。因此,fp.write() 必须支持 str 输入。

If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
如果 ensure_ascii 是 true (即默认值),输出保证将所有输入的非 ASCII 字符转义。如果 ensure_ascii 是 false,这些字符会原样输出。

If check_circular is false (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).
如果 check_circular 是为假值 (默认为 True),那么容器类型的循环引用检验会被跳过并且循环引用会引发一个 OverflowError (或者更糟的情况)。

If allow_nan is false (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification. If allow_nan is true, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used.
如果 allow_nan 是 false (默认为 True),那么在对严格 JSON 规格范围外的 float 类型值 (nan、inf 和 -inf) 进行序列化时会引发一个 ValueError。如果 allow_nan 是 true,则使用它们的 JavaScript 等价形式 (NaN、Infinity 和 -Infinity)。

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or “” will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as \t), that string is used to indent each level.
如果 indent 是一个非负整数或者字符串,那么 JSON 数组元素和对象成员会被美化输出为该值指定的缩进等级。如果缩进等级为零、负数或者 “”,则只会添加换行符。None (默认值) 选择最紧凑的表达。使用一个正整数会让每一层缩进同样数量的空格。如果 indent 是一个字符串(比如 \t),那个字符串会被用于缩进每一层。

If specified, separators should be an (item_separator, key_separator) tuple. The default is (’, ‘, ‘: ‘) if indent is None and (’,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (’,’, ‘:’) to eliminate whitespace.
当指定时,separators 应当是一个 (item_separator, key_separator) 元组。当 indent 为 None 时,默认值取 (’, ', ‘: ‘),否则取 (’,’, ‘: ‘)。为了得到最紧凑的 JSON 表达式,你应该指定其为 (’,’, ‘:’) 以消除空白字符。

If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
当 default 被指定时,其应该是一个函数,每当某个对象无法被序列化时它会被调用。它应该返回该对象的一个可以被 JSON 编码的版本或者引发一个 TypeError。如果没有被指定,则会直接引发 TypeError。

If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.
如果 sort_keys 是 true (默认为 False),那么字典的输出会以键的顺序排序。

To use a custom JSONEncoder subclass (e.g. one that overrides the default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
为了使用一个自定义的 JSONEncoder 子类 (比如:覆盖了 default() 方法来序列化额外的类型),通过 cls 关键字参数来指定;否则将使用 JSONEncoder。

Note Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file.
与 pickle 和 marshal 不同,JSON 不是一个具有框架的协议,所以尝试多次使用同一个 fp 调用 dump() 来序列化多个对象会产生一个不合规的 JSON 文件。

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

Serialize obj to a JSON formatted str using this conversion table. The arguments have the same meaning as in dump().
使用这个转换表将 obj 序列化为 JSON 格式的 str。其参数的含义与 dump() 中的相同。

Note Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.
JSON 中的键-值对中的键永远是 str 类型的。当一个对象被转化为 JSON 时,字典中所有的键都会被强制转换为字符串。这所造成的结果是字典被转换为 JSON 然后转换回字典时可能和原来的不相等。换句话说,如果 x 具有非字符串的键,则有 loads(dumps(x)) != x。

json.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 text file or binary file containing a JSON document) to a Python object using this conversion table.
使用这个 转换表 将 fp (一个支持 .read() 并包含一个 JSON 文档的 text file 或者 binary file) 反序列化为一个 Python 对象。

object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).
object_hook 是一个可选的函数,它会被调用于每一个解码出的对象字面量 (即一个 dict)。object_hook 的返回值会取代原本的 dict。这一特性能够被用于实现自定义解码器 (如 JSON-RPC 的类型提示)。

json.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, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

The other arguments have the same meaning as in load(), except encoding which is ignored and deprecated.
其他参数与load() 的含义相同,但编码会被忽略和弃用。

你可能感兴趣的:(JSON)