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

相关推荐
Манго нектар22 分钟前
JavaScript for循环语句
开发语言·前端·javascript
程序猿小D31 分钟前
第二百六十九节 JPA教程 - JPA查询OrderBy两个属性示例
java·开发语言·数据库·windows·jpa
阿华的代码王国39 分钟前
【JavaEE】——文件IO的应用
开发语言·python
satan–044 分钟前
R语言的下载、安装及环境配置(Rstudio&VSCode)
开发语言·windows·vscode·r语言
电饭叔1 小时前
《python语言程序设计》2018版第8章19题几何Rectangle2D类(下)-头疼的几何和数学
开发语言·python
Eternal-Student1 小时前
everyday_question dq20240731
开发语言·arm开发·php
卑微求AC2 小时前
(C语言贪吃蛇)11.贪吃蛇方向移动和刷新界面一起实现面临的问题
c语言·开发语言
程序猿小D2 小时前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa
Yvemil72 小时前
RabbitMQ 入门到精通指南
开发语言·后端·ruby
潘多编程2 小时前
Java中的状态机实现:使用Spring State Machine管理复杂状态流转
java·开发语言·spring