Python json.dumps() Guide: Encode Objects to JSON
The json.dumps() function is used to encode Python objects into a JSON formatted string. Its usage is as follows:
import json
# 创建一个Python对象
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 使用json.dumps()将Python对象编码为JSON格式的字符串
json_string = json.dumps(data)
# 打印编码后的JSON字符串
print(json_string)
Output result:
{"name": "John", "age": 30, "city": "New York"}
You can customize the encoding process by specifying some parameters. For example, you can use the indent parameter to specify the number of spaces for indentation, making the output JSON string easier to read. An example is shown below:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 使用indent参数指定缩进空格数量为4
json_string = json.dumps(data, indent=4)
print(json_string)
The output is:
{
"name": "John",
"age": 30,
"city": "New York"
}
In addition to the indent parameter, the json.dumps() function also has other optional parameters, such as sort_keys and separators, which can be set according to needs. Detailed usage can be found in the json.dumps() documentation in the Python official documentation.