乐闻世界logo
搜索文章和话题

How to dump a dict to a JSON file?

1个答案

1

To dump a dictionary (dict) to a JSON file, we can use Python's built-in json module. The specific steps are as follows:

  1. Import the json module: First, import the Python json module. This module provides tools for converting dictionaries to JSON-formatted strings.
python
import json
  1. Prepare data: Before saving data to a JSON file, you need to have data structured as a dictionary.
python
data = { "name": "张三", "age": 30, "city": "北京" }
  1. Use the json.dump method: The json.dump method converts dictionary data to JSON format and writes it to a file. You must specify the target file and the data.
python
with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4)

The ensure_ascii=False parameter ensures Chinese characters are preserved in the file, while indent=4 makes the JSON file format more readable.

Simple Example

The following is a complete example demonstrating how to save a dictionary containing personal information to a file named data.json:

python
import json # Data data = { "name": "张三", "age": 30, "city": "北京" } # Write to data.json with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4) print("Data has been successfully written to data.json file.")

After running the above code, you will find a file named data.json in the current directory, with the following content:

json
{ "name": "张三", "age": 30, "city": "北京" }

This method is highly practical in development, especially when saving configuration information, user data, or other structured data to files for subsequent programs to read.

2024年8月9日 02:54 回复

你的答案