python中序列化

#coding: utf-8
import sys, cPickle, json
import msgpack

obj = [[1, 2, 3], 123, 123.123, 'abc', {'键1': (1, 2, 3), '键2': (4, 5, 6)}]
print obj

#使用cPickle序列化
ser = cPickle.dumps(obj,True)
print ser
print cPickle.loads(ser)
#获取此对象在内存中所占的字节数
print sys.getsizeof(ser)

#转为json
ser = json.dumps(obj)
print ser
print sys.getsizeof(ser)

#转为MessagePack
ser = msgpack.packb(obj, use_bin_type=True)
print ser
print msgpack.unpackb(ser, encoding='utf-8')
print sys.getsizeof(ser)

你可能感兴趣的:(python中序列化)