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

相关推荐
weixin_307779131 小时前
Azure上基于OpenAI GPT-4模型验证行政区域数据的设计方案
数据仓库·python·云计算·aws
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
多想和从前一样4 小时前
Django 创建表时 “__str__ ”方法的使用
后端·python·django
ll7788114 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
小喵要摸鱼6 小时前
【Pytorch 库】自定义数据集相关的类
pytorch·python
bdawn6 小时前
深度集成DeepSeek大模型:WebSocket流式聊天实现
python·websocket·openai·api·实时聊天·deepseek大模型·流式输出
Jackson@ML6 小时前
Python数据可视化简介
开发语言·python·数据可视化
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt
赵琳琅6 小时前
Java语言的云计算
开发语言·后端·golang
lly2024066 小时前
jQuery 杂项方法
开发语言