- json只能用于简单的数据类型,例如:字典啊,列表啊,字符串之类的,无法处理复杂的,例如带有函数的
- json适用于所有的开发语言
- dumps与loads只对应使用一次,若dumps多次,则loads出错
- import json json.dumps() and json.loads()
import json info = { "name":"alex", "age": 23 } f = open("test.txt","w",encoding="utf-8") f.write(json.dumps(info)) f.close()
import json f = open("test.txt","r",encoding="utf-8") data = json.loads(f.read()) print(data)
- import json json.dump() and json.load()
import json info = { "name":"alex", "age": 23 } f = open("test.txt","w",encoding="utf-8") json.dump(info,f) #相当于f.write(json.dumps(info)) f.close()
import json f = open("test.txt","r",encoding="utf-8") data = json.load(f)#相当于data = json.loads(f.read()) print(data) f.close()
- import pickle 处理复杂类型:只适用于python
import pickle def func(name): print("name",name) info = { "name":"alex", "age": 23, "function":func } f = open("test.txt","wb") f.write(pickle.dumps(info)) f.close()
import pickle def func(name): print("name",name) print("这里只保存了对应函数的名称,有相应的名称则能使用,里面的内容可以不同") f = open("test.txt","rb") data = pickle.loads(f.read()) print(data) f.close()