json.dumps() 是将 Python 对象序列化为 JSON 格式的字符串。如果你想将 JSON 数据写入文件,可以将 json.dumps() 生成的字符串写入文件,或者更直接地使用 json.dump() 函数,它会直接将 Python 对象序列化写入文件。
下面是两个方法,一是使用 json.dumps() 然后写入文件,二是使用 json.dump() 直接写入文件。
1 2 3 4 5 6 7 8 9 10 |
import json
data = {"name": "Alice", "age": 30, "is_student": False}
# 序列化为 JSON 字符串 json_str = json.dumps(data, indent=4)
# 将 JSON 字符串写入文件 with open('output.json', 'w', encoding='utf-8') as file: file.write(json_str) |
1 2 3 4 5 6 7 |
import json
data = {"name": "Alice", "age": 30, "is_student": False}
# 直接将 JSON 数据写入文件 with open('output.json', 'w', encoding='utf-8') as file: json.dump(data, file, indent=4) |
fp:文件对象,表示要写入的文件。
1 2 3 4 5 6 |
import json
data = {"name": "Alice", "age": 30, "languages": ["English", "French"], "is_student": False}
with open('output.json', 'w', encoding='utf-8') as file: json.dump(data, file, indent=4, ensure_ascii=False, sort_keys=True) |
json.dumps() 的参数可见博客json.dumps的参数