json.dumps() 序列化
JSON序列化是指将对象转化为字节序列的过程。序列化后的数据可以用于在网络上传输或保存到硬盘上。JSON是一种轻量级的数据交换格式,它使用人类可读的文本来表示数据,通常用于数据交换和存储。
json.dumps(): python数据类型转化为json字符串
比如: 将字符串,字典,列表类型的数据转换成json字符串类型的数据
1 2 3 4 5 6 7 8 9 10 11
| import json
data_dict = {"name": "jack Ma", "QQ": ["12345", "abcd"]} data_json = json.dumps(data_dict) print(type(data_json), data_dict)
data_list = [1, 2, 3, 4] data_json = json.dumps(data_list) print(type(data_json), data_json)
|
json.loads() 反序列化
json.loads(): json字符串转化为python数据类型
比如:将json字符串类型的数据转换成列表,字典,字符串类型数据
1 2 3 4 5 6 7 8 9 10 11
| import json
data_json_str = '{"name":"jack ma", "QQ":["12345","abcde"]}' data_dict = json.loads(data_json_str) print(type(data_dict), data_dict)
data_json_str = '[1,2,3,4]' data_list = json.loads(data_json_str) print(type(data_list), data_list)
|
json.load() 和 json.dump()
json.load() : 包含json的类文件对象转化为python数据类型;
json.dump(): python数据类型转化为包含json的类文件对象;
举例1
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import json
file_json = "data_list.json" data_list = [{"city": "nanjing"}, {"name": "zhu"}]
with open(file_json, "w") as fw: json.dump(data_list, fw, ensure_ascii=False)
with open(file_json) as f: get_data_list = json.load(f) print(type(get_data_list), get_data_list)
|
举例2
1 2 3 4 5 6 7 8 9 10 11 12
| import json
file_json = "data_list.json" data_dict = {"city": "nanjing", "name": "ma"}
with open(file_json, "w") as fw: json.dump(data_dict, fw, ensure_ascii=False)
with open(file_json) as f: get_data_dict = json.load(f) print(type(get_data_dict), get_data_dict)
|
注: json文件为防出现中文乱码:ensure_ascii=False
什么是类文件对象?
具有read()或者write()方法的对象就是类文件对象,
file = open("listStr.json", "w") 中 file 就是类文件对象
应用:将txt文件转为json文件
demo1:将txt文本读取到,然后转为json形式,再写入json格式文件。
1 2 3 4 5 6 7 8 9 10 11 12 13
| import json
file_txt = 'test.txt' file_json = 'test.json'
with open(file_txt, 'rb') as fr: content = fr.read().decode('utf8') print(content)
with open(file_json, 'w') as fw: content_json = json.dumps(content) fw.write(content_json)
|
demo2:如果是将一个json文件的内容写到另一个json文件,先将json文本读取,再直接写入另一个json格式文本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import json
file = 'test.json'
newfile = 'newtest.json'
with open(file, 'rb') as fr: if file.endswith('json'): content = json.load(fr) elif file.endswith('txt'): content = fr.read().decode('utf8') print(type(content), content)
with open(newfile, 'w') as fw: json.dump(content, fw)
|