anyjson与simplejson的使用

来源:互联网 发布:淘宝韩国女模特 编辑:程序博客网 时间:2024/06/05 13:23

什么是序列化?把变量从内存中变成可存储或可传输的过程就称之为序列化。在Python中称为picking,在其他语言中称之为serialization,marshalling,flattening等等,都是一个意思。之前学过的json,pickle都可以实现对数据进行序列化,接下来记录一下另外两种实现数据序列化的库。

anyjson

  • 安装
pip install anyjson
  • 序列化
import anyjsoninfo = {"b":1,"a":2}result = anyjson.serialize(info)f = open("file.txt","w")f.write(result)f.close()
  • 反序列化
import anyjsonwith open("file.txt","r") as f:    info = anyjson.deserialize(f.read())

simplejson

  • 安装
pip install simplejson
  • 序列化
import simplejsoninfo = [{"name":"laowang","age":40}]result = simplejson.dumps(info)with open("file.txt","w") as f:    f.write(result)# 或者import simplejsoninfo = [{"name":"laowang","age":40}]with open("file.txt","w") as f:    result = simplejson.dump(info,f)
  • 反序列化
import simplejsonwith open("file.txt","r") as f:    info = f.read()    result = simplejson.loads(info)# 或者import simplejsonwith open("file.txt","r") as f:    info = simplejson.load(f)
  • 排序
import simplejsoninfo = {"b":1,"a":2}# 按key升序result = simplejson.dumps(info,sort_keys=True)  
原创粉丝点击