在Python中,dump
函数通常用于将数据序列化为JSON格式并写入文件中。以下是使用dump
函数的一些示例:
import json
data = {"name": "Alice", "age": 30}
with open("data.json", "w") as file:
json.dump(data, file)
import json
data = ["apple", "banana", "cherry"]
with open("data.json", "w") as file:
json.dump(data, file)
indent
参数将数据格式化并写入JSON文件中:import json
data = {"name": "Alice", "age": 30}
with open("data.json", "w") as file:
json.dump(data, file, indent=4)
sort_keys
参数按键对数据进行排序并写入JSON文件中:import json
data = {"b": 2, "a": 1, "c": 3}
with open("data.json", "w") as file:
json.dump(data, file, sort_keys=True)
这些示例展示了如何使用dump
函数将数据写入JSON文件中,并可以根据需要进行格式化和排序。