共计 1152 个字符,预计需要花费 3 分钟才能阅读完成。
目录
一、json 库介绍
二、字典生成 json 文件
1、导入 json 模块
2、将字典数据保存为 json 文件
(1) 创建一个 python 字典
(2) 指定要保存的 json 文件路径
(3) 将字典数据存为 json 文件
3、读取 json 文件,并打印
一、json 库介绍
方法 | 作用 |
---|---|
json.dumps() | 将 python 对象编码成 Json 字符串 |
json.loads() | 将 Json 字符串解码成 python 对象 |
json.dump() | 将 python 中的对象转化成 json 储存到文件中 |
json.load() | 将文件中的 json 的格式转化成 python 对象提取出来 |
json.dump() 和 json.dumps() 的区别:
- json.dumps() 是把 python 对象转换成 json 对象的一个过程,生成的是字符串;
import json
x = {'name':'你猜','age':19,'city':'四川'}
#用 dumps 将 python 编码成 json 字符串
print(json.dumps(x)) #{"name": "u4f60u731c", "age": 19, "city": "u56dbu5ddd"}
- json.dump() 是把 python 对象转换成 json 对象生成一个 fp 的文件流,和文件相关;
import json
x = {'name':'你猜','age':19,'city':'四川'}
#把 python 编码成 json 放在那个文件里
filename = 'pi_x.txt'
with open (filename,'w') as f:
json.dump(x,f)
二、字典生成 json 文件
1、导入 json 模块
import json
2、将字典数据保存为 json 文件
(1) 创建一个 python 字典
dict_data = {
"name": "Alice",
"age": 25,
"city": "New York"
}
(2) 指定要保存的 json 文件路径
file_path = "test.json"
(3) 将字典数据存为 json 文件
with open(file_path, "w", encoding='utf-8') as json_file:
json.dump(dict_data, json_file)
也可以加上参数,如:json.dump(dict_data, json_file, indent=4, ensure_ascii=False)
json.dump() 函数将字典数据写入指定路径的 JSON 文件中。
3、读取 json 文件,并打印
with open(file_path, "r") as json_file:
loaded_data = json.load(json_file)
print(loaded_data)
打印出读取的数据,确认是否保存成功
原文地址: python 将字典数据保存为 json 文件
正文完