在 Python 中,将字典(dict)转换为 JSON 字符串非常简单,主要使用内置的 json
模块。以下是几种常见的方法:
import json
# 创建一个字典
my_dict = {
"name": "honeymoose",
"age": 30,
"skills": ["Python", "Java", "Go"],
"is_active": True
}
# 转换为JSON字符串
json_str = json.dumps(my_dict)
print(json_str)
# 带缩进的格式化输出
formatted_json = json.dumps(my_dict, indent=4)
print(formatted_json)
# 按ASCII排序输出键
sorted_json = json.dumps(my_dict, sort_keys=True)
print(sorted_json)
默认情况下,json.dumps()
会将非ASCII字符转义。如果要正确显示中文,可以设置 ensure_ascii=False
:
chinese_dict = {
"姓名": "张三",
"城市": "北京"
}
# 正确显示中文
chinese_json = json.dumps(chinese_dict, ensure_ascii=False)
print(chinese_json)
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(my_dict, f, ensure_ascii=False, indent=4)
注意区别:
json.dumps()
返回JSON字符串json.dump()
将JSON数据写入文件对象如果字典中包含自定义类对象,可以通过扩展JSONEncoder类来处理:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if hasattr(obj, 'to_json'):
return obj.to_json()
return super().default(obj)
# 使用自定义编码器
json_str = json.dumps(my_dict, cls=CustomEncoder)
这些是Python中将dict转换为JSON字符串的常用方法,希望对您有所帮助!
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有