快速上手:Python `dict` 转 JSON 的简单示例 – wiki大全

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,因其易于人阅读和编写,同时也易于机器解析和生成,而广泛应用于网络应用和配置文件中。Python 的字典和 JSON 对象在结构上天然对应,使得转换过程非常直接。

Python 内置的 json 模块是处理此类任务的标准库,无需安装任何第三方包。该模块提供了两个核心函数来完成“编码”(从 Python 对象到 JSON)的过程:

  1. json.dumps():将 Python 对象(如 dict)转换为一个 JSON 格式的字符串。这里的 “s” 代表 “string”。
  2. json.dump():将 Python 对象序列化为 JSON 格式,并将其写入一个文件(或任何类似文件的对象)。

接下来,我们将通过具体的示例来详细了解这两个函数的用法。

示例 1: json.dumps() – 将字典转换为 JSON 字符串

这是最常见的用例。当你需要将数据通过 API 发送,或者只是想将其表示为文本时,dumps() 是你的首选。

基础用法

让我们从一个简单的字典开始:

“`python
import json

1. 定义一个 Python 字典

student_data = {
“name”: “张三”,
“age”: 22,
“is_enrolled”: True,
“courses”: [
{“title”: “计算机科学”, “credits”: 3},
{“title”: “数据结构”, “credits”: 4}
]
}

2. 使用 json.dumps() 进行转换

json_string = json.dumps(student_data)

3. 打印结果

print(“转换后的 JSON 字符串:”)
print(json_string)
“`

输出:

转换后的 JSON 字符串:
{"name": "\u5f20\u4e09", "age": 22, "is_enrolled": true, "courses": [{"title": "\u8ba1\u7b97\u673a\u79d1\u5b66", "credits": 3}, {"title": "\u6570\u636e\u7ed3\u6784", "credits": 4}]}

你会注意到两个问题:
– 所有内容都在一行,可读性很差。
– 中文字符被转换成了 Unicode 编码(如 \u5f20\u4e09)。

幸运的是,dumps() 提供了几个非常有用的参数来美化输出。

常用参数

  1. indent:美化输出(Pretty-Printing)
    通过设置 indent 参数,你可以让 JSON 字符串自动缩进,从而极大地提高可读性。通常将其值设为 24

    “`python

    使用 indent 参数

    pretty_json_string = json.dumps(student_data, indent=4)
    print(“\n美化后的 JSON 字符串:”)
    print(pretty_json_string)
    “`

  2. ensure_ascii=False:正确显示非 ASCII 字符
    默认情况下,json 模块会转义所有非 ASCII 字符。要让中文、日文或其他语言的字符直接显示,你需要将 ensure_ascii 设置为 False

    “`python

    结合 indent 和 ensure_ascii

    readable_json_string = json.dumps(student_data, indent=4, ensure_ascii=False)
    print(“\n正确显示中文并美化后的 JSON 字符串:”)
    print(readable_json_string)
    “`

    输出:
    json
    正确显示中文并美化后的 JSON 字符串:
    {
    "name": "张三",
    "age": 22,
    "is_enrolled": true,
    "courses": [
    {
    "title": "计算机科学",
    "credits": 3
    },
    {
    "title": "数据结构",
    "credits": 4
    }
    ]
    }

    现在这个输出就非常清晰易读了。

  3. sort_keys=True:对键进行排序
    如果你希望输出的 JSON 对象的键是按字母顺序排列的,可以设置 sort_keys=True。这对于比较不同的 JSON 对象非常有用。

    python
    sorted_json_string = json.dumps(student_data, indent=4, ensure_ascii=False, sort_keys=True)
    print("\n对键排序后的 JSON 字符串:")
    print(sorted_json_string)

    输出 (注意 “age” 排在了 “courses” 前面):
    json
    对键排序后的 JSON 字符串:
    {
    "age": 22,
    "courses": [
    {
    "credits": 3,
    "title": "计算机科学"
    },
    {
    "credits": 4,
    "title": "数据结构"
    }
    ],
    "is_enrolled": true,
    "name": "张三"
    }

示例 2: json.dump() – 将字典写入 JSON 文件

当你需要将配置、数据或程序状态持久化到文件中时,dump() 函数就派上用场了。它直接将字典内容写入一个文件对象,而不是先在内存中创建一个字符串。

“`python
import json

同样使用上面的 student_data 字典

student_data = {
“name”: “张三”,
“age”: 22,
“is_enrolled”: True,
“courses”: [
{“title”: “计算机科学”, “credits”: 3},
{“title”: “数据结构”, “credits”: 4}
]
}

1. 指定文件名

output_file = “student.json”

2. 使用 ‘with open’ 安全地打开文件并写入

‘w’ 表示写入模式,encoding=’utf-8′ 对于包含非 ASCII 字符的文件至关重要

with open(output_file, ‘w’, encoding=’utf-8′) as f:
# 3. 使用 json.dump() 写入数据
# 它也支持 indent 和 ensure_ascii 等参数
json.dump(student_data, f, indent=4, ensure_ascii=False)

print(f”\n数据已成功写入到文件 ‘{output_file}’ 中。”)
“`

执行这段代码后,你的项目目录下会生成一个名为 student.json 的文件,其内容与前面 dumps() 美化后的输出完全相同。

数据类型对应关系

json 模块在转换时会自动处理 Python 内置类型与 JSON 类型的映射关系:

Python JSON
dict object
list, tuple array
str string
int, float number
True / False true / false
None null

总结

将 Python 字典转换为 JSON 是一个非常简单直接的过程:

  • 转换为字符串:使用 json.dumps()。这是最常用的方法,尤其是在处理网络请求时。
  • 写入文件:使用 json.dump()。当你需要将数据持久化存储时使用。
  • 美化与中文支持:始终记得使用 indent 参数来提高可读性,并使用 ensure_ascii=False 来正确处理中文字符。

掌握了 json 模块的这些基本用法,你就可以轻松地在 Python 程序中处理各种与 JSON 相关的任务了。

滚动至顶部