anyjson与simplejson的使用

什么是序列化?把变量从内存中变成可存储或可传输的过程就称之为序列化。在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)  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值