如何在 Python 中读取和解析 JSON 文件

了解如何使用内置 json 模块在 Python 中读取、解析和加载 JSON 文件。掌握将 JSON 字符串转换为字典,反之亦然。

在编辑器中尝试此解决方案

概述

JSON(JavaScript 对象表示法)是 API、配置文件和数据存储中最流行的数据格式。 Python 附带了一个内置的“json”模块,使读取、解析和写入 JSON 数据变得异常简单。由于 JSON 对象完美映射到 Python 字典,而 JSON 数组映射到 Python 列表,因此使用 JSON 感觉很自然。

要从外部文件读取 JSON,您可以使用 json.load() 函数,该函数解析文件流并将 JSON 结构转换为 Python 数据类型。如果 JSON 数据已作为字符串加载到内存中,则可以使用“json.loads()”函数(“s”代表字符串)。选择正确的函数可以防止解析器崩溃。

使用 JSON 时,最佳做法是处理编码和潜在的格式错误。在 `open()` 语句中使用 `encoding="utf-8"` 可防止您的脚本因特殊字符而失败。将文件操作包装在捕获“json.JSONDecodeError”的“try- except”块中,可确保您的应用程序在 JSON 文件格式错误时正常降级。

代码和执行输出

此代码演示了如何编写示例 JSON 文件、将其读取并解析回 Python 字典,以及处理 JSON 字符串。

import json

# Let's write a mock JSON file first
sample_data = {
    "user": "developer123",
    "skills": ["python", "javascript", "sql"],
    "active": True
}
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(sample_data, f, indent=4)

# 1. Reading from a JSON file (using json.load)
with open("data.json", "r", encoding="utf-8") as file:
    data_from_file = json.load(file)
    print("File Content type:", type(data_from_file).__name__)
    print("User skill list:", data_from_file["skills"])

# 2. Reading from a JSON string (using json.loads)
json_string = '{"host": "localhost", "port": 5432, "ssl": false}'
data_from_str = json.loads(json_string)
print("\nString Content type:", type(data_from_str).__name__)
print("Database host:", data_from_str["host"])
端子输出
File Content type: dict
User skill list: ['python', 'javascript', 'sql']

String Content type: dict
Database host: localhost

逐步实施

  • 在脚本中导入内置 json 模块。
  • 使用 with open("filename.json", "r",encoding="utf-8") 作为文件打开 JSON 文件。
  • 将文件对象传递给 json.load(file) 以将内容解析为 Python 字典。
  • 如果需要解析已加载到内存中的原始 JSON 字符串,请使用 json.loads(string_data)。

常见问题解答

json.load() 和 json.loads() 有什么区别?

json.load() 接受类似文件的流对象(从磁盘读取),而 json.loads() 接受包含 JSON 内容的标准字符串或字节对象(从内存读取)。

如何处理自定义类的 JSON 序列化错误?

Python 的 json 模块默认无法序列化自定义类实例。您必须提供一个扩展 json.JSONEncoder 的自定义编码器类,或者首先使用辅助方法将实例的属性提取到字典中。

相关主题

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。