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

相关推荐
一颗知足的心5 分钟前
Go语言之路————指针、结构体、方法
开发语言·后端·golang
yuanpan15 分钟前
C#如何正确的停止一个多线程Task?CancellationTokenSource 的用法。
开发语言·c#
程高兴18 分钟前
单相交直交变频电路设计——matlab仿真+4500字word报告
开发语言·matlab
hyhrosewind42 分钟前
Python函数基础:说明文档(多行注释),函数嵌套调用,变量作用域(局部,全局,global关键字),综合案例
python·变量作用域·函数说明文档(多行注释)·函数嵌套调用·局部变量和全局变量·函数内修改全局变量·global关键字
我真的不会C1 小时前
QT中的事件及其属性
开发语言·qt
一点.点1 小时前
李沐动手深度学习(pycharm中运行笔记)——04.数据预处理
pytorch·笔记·python·深度学习·pycharm·动手深度学习
一点.点1 小时前
李沐动手深度学习(pycharm中运行笔记)——07.自动求导
pytorch·笔记·python·深度学习·pycharm·动手深度学习
2501_906314322 小时前
优化无头浏览器流量:使用Puppeteer进行高效数据抓取的成本降低策略
开发语言·数据结构·数据仓库
让我们一起加油好吗2 小时前
【C++】类和对象(上)
开发语言·c++·visualstudio·面向对象
大霸王龙2 小时前
Python对比两张CAD图并标记差异的解决方案
python·opencv·计算机视觉