标签:seh bytes binary should iii key ecif term json.js
内容目录
JSON是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。
编码:把一个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) 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 } ]
json.loads
(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) str
instance containing a JSON document) to a Python object using this conversion table.load()
, except encoding which is ignored and deprecated.JSONDecodeError
will be raised.st1 = ‘{"__complex__": true, "real": 1, "imag": 2}‘ ret = json.loads(st1) print(ret) # {‘real‘: 1, ‘__complex__‘: True, ‘imag‘: 2}
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) .write()
-supporting file-like object) using this conversion table.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
.json
module always produces str
objects, not bytes
objects. Therefore, fp.write()
must support str
input.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.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).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
).""
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.(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.(‘,‘, ‘: ‘)
as default if indent is not None
.TypeError
. The default simply raises TypeError
.True
(default: False
), then the output of dictionaries will be sorted by key.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)
处理文件解码
json.load
(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) .read()
-supporting file-like object containing a JSON document) to a Python object using this conversion table.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).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.float(num_str)
. This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal
).int(num_str)
. This can be used to use another datatype or parser for JSON integers (e.g. float
).‘-Infinity‘
, ‘Infinity‘
, ‘NaN‘
. This can be used to raise an exception if invalid JSON numbers are encountered.JSONDecoder
subclass, specify it with the cls
kwarg; otherwise JSONDecoder
is used. Additional keyword arguments will be passed to the constructor of the class.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‘>
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模块的反序列化操作,能从文件中创建上次保存的对象。
import pickle li = [1, 2, 3] r = pickle.dumps(li) print(r) # b‘\x80\x03]q\x00(K\x01K\x02K\x03e.‘
pickle.loads
(bytes_object, *, fix_imports=True, encoding="ASCII", errors="strict") bytes
object and return the reconstituted object hierarchy specified therein.r = pickle.loads(r) print(r) # [1, 2, 3]
pickle.dump
(obj, file, protocol=None, *, fix_imports=True) Pickler(file, protocol).dump(obj)
.HIGHEST_PROTOCOL
. If not specified, the default is DEFAULT_PROTOCOL
. If a negative number is specified, HIGHEST_PROTOCOL
is selected.io.BytesIO
instance, or any other custom object that meets this interface.pickle.load
(file, *, fix_imports=True, encoding="ASCII", errors="strict") Unpickler(file).load()
.io.BytesIO
object, or any other custom object that meets this interface.import pickle li = [1, 2, 3] pickle.dump(li, open(‘db‘, ‘wb‘)) ret = pickle.load(open(‘db‘, ‘rb‘)) print(ret)
标签:seh bytes binary should iii key ecif term json.js
原文地址:http://www.cnblogs.com/xiaoming279/p/6372870.html