码迷,mamicode.com
首页 > 编程语言 > 详细

python的json序列化

时间:2018-05-15 10:40:34      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:序列化   eval   bsp   name   pre   print   序列   使用   def   

  

    
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序列化

标签:序列化   eval   bsp   name   pre   print   序列   使用   def   

原文地址:https://www.cnblogs.com/wherewhenwho/p/9035335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!