csdn/CSDN博文备份/Pythondict转换为JSON字符串的方法-146410216.md
2025-03-21 02:19:41 +08:00

1 line
2.7 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<p>在 Python 中,将字典(dict)转换为 JSON 字符串非常简单,主要使用内置的 <code>json</code> 模块。以下是几种常见的方法:</p> <br><h3>1. 使用 json.dumps()</h3> <br><p></p> <br><pre><code>import json<br><br># 创建一个字典<br>my_dict = {<br> "name": "honeymoose",<br> "age": 30,<br> "skills": ["Python", "Java", "Go"],<br> "is_active": True<br>}<br><br># 转换为JSON字符串<br>json_str = json.dumps(my_dict)<br>print(json_str)<br></code></pre> <br><h3>2. 格式化输出 JSON</h3> <br><p></p> <br><pre><code># 带缩进的格式化输出<br>formatted_json = json.dumps(my_dict, indent=4)<br>print(formatted_json)<br><br># 按ASCII排序输出键<br>sorted_json = json.dumps(my_dict, sort_keys=True)<br>print(sorted_json)<br></code></pre> <br><h3>3. 处理中文</h3> <br><p>默认情况下,<code>json.dumps()</code> 会将非ASCII字符转义。如果要正确显示中文可以设置 <code>ensure_ascii=False</code></p> <br><p></p> <br><pre><code>chinese_dict = {<br> "姓名": "张三",<br> "城市": "北京"<br>}<br><br># 正确显示中文<br>chinese_json = json.dumps(chinese_dict, ensure_ascii=False)<br>print(chinese_json)<br></code></pre> <br><h3>4. 将JSON字符串写入文件</h3> <br><p></p> <br><pre><code>with open('data.json', 'w', encoding='utf-8') as f:<br> json.dump(my_dict, f, ensure_ascii=False, indent=4)<br></code></pre> <br><p>注意区别:</p> <br><ul><li><code>json.dumps()</code> 返回JSON字符串</li><li><code>json.dump()</code> 将JSON数据写入文件对象</li></ul> <br><h3>5. 自定义JSON编码</h3> <br><p>如果字典中包含自定义类对象可以通过扩展JSONEncoder类来处理</p> <br><p></p> <br><pre><code>class CustomEncoder(json.JSONEncoder):<br> def default(self, obj):<br> if hasattr(obj, 'to_json'):<br> return obj.to_json()<br> return super().default(obj)<br><br># 使用自定义编码器<br>json_str = json.dumps(my_dict, cls=CustomEncoder)<br></code></pre> <br><p>这些是Python中将dict转换为JSON字符串的常用方法希望对您有所帮助</p> <br><p></p> <br><p class="img-center"><a href="https://cdn.isharkfly.com/com-isharkfly-www/discourse-uploads/original/3X/7/a/7a0f762bcf73f9ef923c15492c5c5580aae0d81f.png" rel="nofollow"><img alt="python-json-load-loads-dump-dumps" height="470" src="https://i-blog.csdnimg.cn/img_convert/a654279928d2db9aa0ba2b826f695d5c.png" width="690" /></a></p> <br><p></p> <br><p><a href="https://www.isharkfly.com/t/python-json/17098/3" rel="nofollow" title="Python字典转JSON字符串的方法 - #3 by honeymoose - Python - iSharkFly">Python字典转JSON字符串的方法 - #3 by honeymoose - Python - iSharkFly</a></p>