Python 中的序列化库


Author: yifei / Created: May 30, 2017, 9:47 a.m. / Modified: May 30, 2017, 9:49 a.m. / Edit

basic usage

pickle.dumps(obj)  # dumps a object to a bytes, not binary safe
pickle.loads(bytes)  # loads a object from a bytes.

tricks

pickling dict is stable

In [5]: pickle.dumps({'a': 'b', '1': '2'})
Out[5]: b'\x80\x03}q\x00(X\x01\x00\x00\x001q\x01X\x01\x00\x00\x002q\x02X\x01\x00\x00\x00aq\x03X\x01\x00\x00\x00bq\x04u.'

In [6]: pickle.dumps({'1': '2', 'a': 'b'})
Out[6]: b'\x80\x03}q\x00(X\x01\x00\x00\x001q\x01X\x01\x00\x00\x002q\x02X\x01\x00\x00\x00aq\x03X\x01\x00\x00\x00bq\x04u.'

json

json.dumps(dict,
    sort_keys=True,  # keys will be in order
)

有任何问题可以发邮件到 kongyifei (at) gmail.com 讨论