在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文件中,并可以根據需要進行格式化和排序。