Python 使用 json.dumps 字典转 JSON 时保留双引号并格式化
在 Python 中使用 json.dumps 将字典转换为 JSON 时,默认情况下会将字符串中的双引号转义为单引号。如果需要保留字典字符串中的双引号并格式化 JSON 内容,可以使用参数 ensure_ascii=False 来保留双引号,并使用参数 indent 来格式化 JSON。
示例代码如下:
import json
data = {'name': 'John', 'age': 30, 'city': 'New York', 'description': 'He said, 'I am happy.''}
json_str = json.dumps(data, ensure_ascii=False, indent=4)
print(json_str)
输出结果:
{
"name": "John",
"age": 30,
"city": "New York",
"description": "He said, 'I am happy.'"
}
可以看到,字典字符串中的双引号被保留了,并且 JSON 格式化了。
原文地址: https://www.cveoy.top/t/topic/nCP8 著作权归作者所有。请勿转载和采集!