首页 > 代码库 > json和pickle模块

json和pickle模块

内容目录

一、JSON 1

1.1 json.dumps() 1

1.2 json.loads() 2

1.3 json.dump() 2

1.4 json.load() 3

1.5 编码解码规则 5

二、pickle 5

2.1 pickle.dumps() 5

2.2 pickle.loads() 5

2.3 pickle.dump() 6

2.3 pickle.load() 6

一、JSON

JSON是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。

1.1 json.dumps()

编码:把一个Python对象编码转换成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().
压缩
import json
li = [1, 2, 3, {‘4‘: 5, ‘6‘: 7}]
ret = json.dumps(li, separators=(‘,‘, ‘:‘), sort_keys=True)
print(ret)  # [1,2,3,{"4":5,"6":7}]
缩进
import json
li = [1, 2, 3, {‘4‘: 5, ‘6‘: 7}]
ret = json.dumps(li,indent=4)
print(ret)
[
    1,
    2,
    3,
    {
        "6": 7,
        "4": 5
}
]
排序
import json
li = [1, 2, 3, {‘4‘: 5, ‘6‘: 7}]
ret = json.dumps(li, indent=4, sort_keys=True)
print(ret)
[
    1,
    2,
    3,
    {
        "4": 5,
        "6": 7
}
]

1.2 json.loads()

解码:把json格式字符串转换成Python对象

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 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.
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
st1 = ‘{"__complex__": true, "real": 1, "imag": 2}‘
ret = json.loads(st1)
print(ret)  # {‘real‘: 1, ‘__complex__‘: True, ‘imag‘: 2}

1.3 json.dump()

处理文件编码

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.
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.
The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.
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.
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).
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, instead of using the JavaScript equivalents (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.
Changed in version 3.2: Allow strings for indent in addition to integers.
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.
Changed in version 3.4: Use (‘,‘, ‘: ‘) as default if indent is not None.
default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
If sort_keys is True (default: False), then the output of dictionaries will be sorted by key.
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.
li = [1, 2, 3]
json.dump(li, open(‘db‘, ‘w‘))
with open(‘db1‘, ‘w‘) as f:
json.dump(li, f)

1.4 json.load()

处理文件解码

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 file-like object containing a JSON document) to a Python object using this conversion table.
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_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.
Changed in version 3.1: Added support for object_pairs_hook.
parse_float, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal).
parse_int, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float).
parse_constant, if specified, will be called with one of the following strings: ‘-Infinity‘, ‘Infinity‘, ‘NaN‘. This can be used to raise an exception if invalid JSON numbers are encountered.
Changed in version 3.1: parse_constant doesn’t get called on ‘null’, ‘true’, ‘false’ anymore.
To use a custom JSONDecoder subclass, specify it with the cls kwarg; otherwise JSONDecoder is used. Additional keyword arguments will be passed to the constructor of the class.
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
li = [1, 2, 3]
ret = json.load(open(‘db‘, ‘r‘))
print(ret, type(li))  # [1, 2, 3] <class ‘list‘>
with open(‘db1‘, ‘r‘) as f:
    ret = json.load(f)
print(ret, type(ret))  # [1, 2, 3] <class ‘list‘>

1.5 编码解码规则

技术分享 技术分享









 

pickle

The pickle module implements binary protocols for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” [1] or “flattening”; however, to avoid confusion, the terms used here are “pickling” and “unpickling”.

pickle模块实现了序列化和反序列化python对象结构。通过python模块的序列化操作能将程序中运行的对象信息保存到文件中,永久存储;通过pickle模块的反序列化操作,能从文件中创建上次保存的对象。

2.1 pickle.dumps()

pickle.dumps(obj, protocol=None, *, fix_imports=True)
Return the pickled representation of the object as a bytes object, instead of writing it to a file.
Arguments protocol and fix_imports have the same meaning as in dump().
import pickle
li = [1, 2, 3]
r = pickle.dumps(li)
print(r)  # b‘\x80\x03]q\x00(K\x01K\x02K\x03e.‘

2.2 pickle.loads()

pickle.loads(bytes_object, *, fix_imports=True, encoding="ASCII", errors="strict")
Read a pickled object hierarchy from a bytes object and return the reconstituted object hierarchy specified therein.
The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled object’s representation are ignored.
Optional keyword arguments are fix_imports, encoding and errors, which are used to control compatibility support for pickle stream generated by Python 2. If fix_imports is true, pickle will try to map the old Python 2 names to the new names used in Python 3. The encoding and errors tell pickle how to decode 8-bit string instances pickled by Python 2; these default to ‘ASCII’ and ‘strict’, respectively. The encoding can be ‘bytes’ to read these 8-bit string instances as bytes objects.
r = pickle.loads(r)
print(r)  # [1, 2, 3]

2.3 pickle.dump()

pickle.dump(obj, file, protocol=None, *, fix_imports=True)
Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj).
The optional protocol argument, an integer, tells the pickler to use the given protocol; supported protocols are 0 to HIGHEST_PROTOCOL. If not specified, the default is DEFAULT_PROTOCOL. If a negative number is specified, HIGHEST_PROTOCOL is selected.
The file argument must have a write() method that accepts a single bytes argument. It can thus be an on-disk file opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface.
If fix_imports is true and protocol is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2.

2.3 pickle.load()

pickle.load(file, *, fix_imports=True, encoding="ASCII", errors="strict")
Read a pickled object representation from the open file object file and return the reconstituted object hierarchy specified therein. This is equivalent to Unpickler(file).load().
The protocol version of the pickle is detected automatically, so no protocol argument is needed. Bytes past the pickled object’s representation are ignored.
The argument file must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus file can be an on-disk file opened for binary reading, an io.BytesIO object, or any other custom object that meets this interface.
Optional keyword arguments are fix_imports, encoding and errors, which are used to control compatibility support for pickle stream generated by Python 2. If fix_imports is true, pickle will try to map the old Python 2 names to the new names used in Python 3. The encoding and errors tell pickle how to decode 8-bit string instances pickled by Python 2; these default to ‘ASCII’ and ‘strict’, respectively. The encoding can be ‘bytes’ to read these 8-bit string instances as bytes objects.
import pickle
li = [1, 2, 3]
pickle.dump(li, open(‘db‘, ‘wb‘))
ret = pickle.load(open(‘db‘, ‘rb‘))
print(ret)


json和pickle模块