Python面试题:如何在 Python 中读取和写入 JSON 文件?

在 Python 中读取和写入 JSON 文件可以使用 json 模块。以下是具体的示例,展示了如何读取和写入 JSON 文件。

读取 JSON 文件

要读取 JSON 文件,可以使用 json.load() 方法。下面是一个示例代码:

python 复制代码
import json

# 假设有一个名为 data.json 的 JSON 文件,其内容如下:
# {
#     "name": "John",
#     "age": 30,
#     "city": "New York"
# }

# 打开 JSON 文件并读取数据
with open('data.json', 'r') as file:
    data = json.load(file)

# 打印读取的数据
print(data)
print(data['name'])
print(data['age'])
print(data['city'])

写入 JSON 文件

要将数据写入 JSON 文件,可以使用 json.dump() 方法。下面是一个示例代码:

python 复制代码
import json

# 要写入的数据
data = {
    "name": "Jane",
    "age": 25,
    "city": "Los Angeles"
}

# 打开一个文件以写入数据
with open('output.json', 'w') as file:
    json.dump(data, file, indent=4)  # indent 参数用于美化输出的 JSON 数据

# 写入完成后,可以检查 output.json 文件以确认数据已成功写入

示例代码解释

  1. 导入模块

    python 复制代码
    import json

    json 模块提供了用于处理 JSON 数据的方法。

  2. 读取 JSON 文件

    python 复制代码
    with open('data.json', 'r') as file:
        data = json.load(file)
    • open('data.json', 'r') 打开名为 data.json 的文件进行读取。
    • json.load(file) 读取文件并将 JSON 数据转换为 Python 字典。
  3. 打印读取的数据

    python 复制代码
    print(data)

    读取的数据存储在变量 data 中,并打印出来。

  4. 写入 JSON 文件

    python 复制代码
    with open('output.json', 'w') as file:
        json.dump(data, file, indent=4)
    • open('output.json', 'w') 打开名为 output.json 的文件进行写入。如果文件不存在,将创建一个新文件。
    • json.dump(data, file, indent=4) 将 Python 字典 data 写入文件。indent=4 参数使输出的 JSON 数据格式化,以便于阅读。

读取和写入 JSON 字符串

有时你可能需要处理 JSON 字符串而不是文件。在这种情况下,可以使用 json.loads()json.dumps() 方法。

示例代码
python 复制代码
import json

# JSON 字符串
json_str = '{"name": "Alice", "age": 28, "city": "Chicago"}'

# 将 JSON 字符串转换为 Python 字典
data = json.loads(json_str)
print(data)

# 将 Python 字典转换为 JSON 字符串
json_str = json.dumps(data, indent=4)
print(json_str)

这些方法使得在 Python 中读取和写入 JSON 文件非常简单和高效。

相关推荐
Despacito0o3 分钟前
C语言基础:变量与进制详解
java·c语言·开发语言
nightunderblackcat24 分钟前
进阶向:人物关系三元组,解锁人物关系网络的钥匙
开发语言·python·开源·php
站大爷IP40 分钟前
Pandas与NumPy:Python数据处理的双剑合璧
python
MrSkye42 分钟前
🔥React 新手必看!useRef 竟然不能触发 onChange?原来是这个原因!
前端·react.js·面试
站大爷IP1 小时前
Python枚举进化论:IntEnum与StrEnum的实战指南
python
甄超锋1 小时前
python sqlite3模块
jvm·数据库·python·测试工具·django·sqlite·flask
科大饭桶2 小时前
C++入门自学Day11-- String, Vector, List 复习
c语言·开发语言·数据结构·c++·容器
范范之交2 小时前
JavaScript基础语法two
开发语言·前端·javascript
Felven2 小时前
C. Game of Mathletes
c语言·开发语言
点云SLAM2 小时前
C++中内存池(Memory Pool)详解和完整示例
开发语言·c++·内存管理·内存池·new/delete·malloc/free