什么是序列化?把变量从内存中变成可存储或可传输的过程就称之为序列化。在Python中称为picking,在其他语言中称之为serialization,marshalling,flattening等等,都是一个意思。之前学过的json,pickle都可以实现对数据进行序列化,接下来记录一下另外两种实现数据序列化的库。
anyjson
- 安装
pip install anyjson
- 序列化
import anyjson
info = {"b":1,"a":2}
result = anyjson.serialize(info)
f = open("file.txt","w")
f.write(result)
f.close()
- 反序列化
import anyjson
with open("file.txt","r") as f:
info = anyjson.deserialize(f.read())
simplejson
- 安装
pip install simplejson
- 序列化
import simplejson
info = [{"name":"laowang","age":40}]
result = simplejson.dumps(info)
with open("file.txt","w") as f:
f.write(result)
# 或者
import simplejson
info = [{"name":"laowang","age":40}]
with open("file.txt","w") as f:
result = simplejson.dump(info,f)
- 反序列化
import simplejson
with open("file.txt","r") as f:
info = f.read()
result = simplejson.loads(info)
# 或者
import simplejson
with open("file.txt","r") as f:
info = simplejson.load(f)
- 排序
import simplejson
info = {"b":1,"a":2}
# 按key升序
result = simplejson.dumps(info,sort_keys=True)