Python json和pickle模块

时间:2022-05-05 22:37:49

1.json------loads/dumps

import json

dic_str = '{"k1":"v1"}'
ret = json.loads(dic_str)
print (ret,type(ret))

dic = {"k1":"v1"}
result = json.dumps(dic)         
print (result,type(result))

loads把字符串转换成字典,dumps用于把字典转换成字符串

2.json------load/dump

dic = {"k1":"v1"}
ret = json.dump(dic,open("jsontest","w"))

ret = json.load(open("jsontest","r"))
print (ret)

dump把字典转换为字符串形式,并且写入到文件中去,load把字符串从文件中读出来,并且转化为字典形式

3.pickle------loads/dumps

dic = {"k1":"v1"}
ret = pickle.dumps(dic)
print (ret,type(ret))

result = pickle.loads(ret)
print (result,type(result))

  b'\x80\x03}q\x00X\x02\x00\x00\x00k1q\x01X\x02\x00\x00\x00v1q\x02s.' <class 'bytes'>
  {'k1': 'v1'} <class 'dict'>

4.pickle------load/dump

dic = {"k1":"v1"}
pickle.dump(dic,open("picktest","wb"))

ret = pickle.load(open("picktest","rb"))
print (ret,type(ret))

5.json/pickle区别

json只能处理基本数据类型,适用于各种语言之间的字符转换

pickle只能处理python的所有数据类型转换