用于序列化的两个模块:
json: 用于字符串和python数据类型间进行转换
pickle: 用于python特有的类型和python的数据类型间进行转换
区别:
Json模块提供了四个功能:dumps、dump、loads、load
pickle模块提供了四个功能:dumps、dump、loads、load
json是可以在不同语言之间交换数据的,而pickle只在python之间使用。
json只能序列化最基本的数据类型,josn只能把常用的数据类型序列化(列表、字典、列表、字符串、数字、),比如日期格式、类对象!josn就不行了。
pickle可以序列化所有的数据类型,包括类,函数都可以序列化。
json
ref
dumps把数据类型转换成字符串
dump把数据类型转换成字符串并存储在文件中
loads把字符串转换成数据类型
load把文件打开从字符串转换成数据类型
库
import json
函数
json.dumps # 将 Python 对象编码成 JSON 字符串(序列化)
test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
print(test_dict)
print(type(test_dict))
#dumps 将数据转换成字符串
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str))
json.loads # 将已编码的 JSON 字符串解码为 Python 对象(反序列化)
new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict))
json.dump # 将数据写入json文件中(序列化)
with open("../config/record.json","w") as f:
json.dump(new_dict,f)
print("加载入文件完成...")
json.load # 把文件打开,并把字符串变换为数据类型(反序列化)
with open("../config/record.json",'r') as load_f:
load_dict = json.load(load_f)
print(load_dict)
load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}]
print(load_dict)
with open("../config/record.json","w") as dump_f:
json.dump(load_dict,dump_f)
当读取的文件为空时,使用try catch 捕获异常
try:
with open('tmp.json', 'r') as f:
k=json.load(f)
print(k)
except json.decoder.JSONDecodeError:
print("empty!")
格式转化表
JSON中的数据格式和Python中的数据格式转化关系如下:
JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None