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 文件非常简单和高效。

相关推荐
databook4 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室5 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三6 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427119 小时前
Python之语言特点
python
刘立军10 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
天天扭码10 小时前
来全面地review一下Flex布局(面试可用)
前端·css·面试
Mor_11 小时前
UE5 网络通信协议学习笔记
面试
沐怡旸11 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
前端缘梦11 小时前
Vue Keep-Alive 组件详解:优化性能与保留组件状态的终极指南
前端·vue.js·面试
前端付豪13 小时前
1、震惊!99% 前端都没搞懂的 JavaScript 类型细节
前端·javascript·面试