python的json序列化
Posted wherewhenwho
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的json序列化相关的知识,希望对你有一定的参考价值。
info = {
"name":"roger",
"age":12
}
f = open("test.txt","w")
f.write(str(info))
f.close()
f = open("test.txt","r")
data = f.read()
print(data["name"])
f.close()
会报错
使用eval()
f = open("test.txt","r")
data = f.read()
print(eval(data)["name"])
f.close()
用json的方式
import json
info = {‘name‘:‘roger‘,‘age‘:12}
print(json.dumps(info))
f = open("test.txt","w")
f.write(json.dumps(info))
import json
f = open("test.txt","r")
data = json.loads(f.read())
print(data["age"])
f.close()
再来一例子:pic
import pickle
def functest():
pass
info = {‘name‘:‘roger‘,‘age‘:12,‘func‘:functest}
print(pickle.dumps(info))
f = open("test.txt","wb")
f.write(pickle.dumps(info))
import pickle
def functest():
pass
f = open("test.txt","rb")
data = pickle.loads(f.read())
print(data["age"])
f.close()
再来一例子
import pickle
def functest():
pass
info = {‘name‘:‘roger‘,‘age‘:12,‘func‘:functest}
print(pickle.dumps(info))
f = open("test.txt","wb")
f.write(pickle.dumps(info))
import pickle
def functest():
print("test")
f = open("test.txt","rb")
data = pickle.loads(f.read())
print(data["func"]())
f.close()
上面的也可以这写:
import pickle
def functest():
pass
info = {‘name‘:‘roger‘,‘age‘:12,‘func‘:functest}
f = open("test.txt","wb")
pickle.dump(info,f)
f.close()
import pickle
def functest():
print("test")
f = open("test.txt","rb")
data = pickle.load(f)
print(data["func"]())
f.close()
记住:dump一次,load一次。
以上是关于python的json序列化的主要内容,如果未能解决你的问题,请参考以下文章
golang的xorm如何将[]map[string][]byte 格式的数据序列化成json输出