import json
# 示例数据:一个包含字符串、数字、布尔值和嵌套列表与字典的Python字典
data = {
"name": "Alice",
"age": 30,
"is_student": False,
"courses": ["Math", "Science"],
"address": {
"street": "123 Main St",
"city": "Beijing"
}
}
# 使用 json.dumps 将 Python 对象转换为 JSON 字符串
json_string = json.dumps(data, ensure_ascii=False, indent=4)
# 输出 JSON 字符串
print(json_string)
json.dumps()
函数用于将 Python 对象(如字典、列表等)转换为 JSON 格式的字符串。ensure_ascii=False
参数确保非 ASCII 字符(例如中文字符)能够正确显示,而不是被转义为 Unicode 形式。indent=4
参数指定了缩进级别为 4 个空格,使生成的 JSON 字符串更易读。如果不指定 indent
,生成的 JSON 字符串将是紧凑格式,没有换行和缩进。上一篇:asyncio python
下一篇:python的输入函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站