Python的json and pickle序列化

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python的json and pickle序列化相关的知识,希望对你有一定的参考价值。

json序列化和json反序列化

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 人生入戏
import json

a = {
    "name":"test",
    "age":"20",
}
#json序列化
with open("json_test","w",encoding="utf-8") as f:
    f.write(json.dumps(a)) # 等同于这个 json.dump(a,f)

#json反序列化
with open("json_test","r",encoding="utf-8") as f:
    print(json.loads(f.read())) #等同于这个  print(json.load(f))

pickle序列化和反序列化

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 人生入戏
import pickle

def hello():
    print("Hello!")
    return 0
a = {
    "name":"test",
    "age":"20",
    "func":hello
}
with open("json_test","wb") as f:
    f.write(pickle.dumps(a))  #等同于这个 pickle.dump(a,f)

with open("json_test","rb") as f:
    print(pickle.loads(f.read())["func"]()) #等同于这个 print(pickle.load(f)["func"]())

 

以上是关于Python的json and pickle序列化的主要内容,如果未能解决你的问题,请参考以下文章

Python的json and pickle序列化

Python学习之路:son and pickle序列化

python--json与pickle序列化

json和pickle

python 序列化 json pickle

[]Python][simple]Serialize data with Pickle and deserialize data from pickle