
本文介绍了如何使用 Python 将一个包含多个 JSON 对象的 JSON 文件,分割成多个独立的文件,每个文件包含一个 JSON 对象。通过 json 模块的 load 和 dump 函数,可以轻松读取 JSON 文件内容并将其写入到多个文件中,实现数据的拆分和管理。
假设我们有一个名为 data.json 的 JSON 文件,其内容是一个包含多个 JSON 对象的数组。我们需要将这个文件分割成多个文件,每个文件对应数组中的一个 JSON 对象,并命名为 data_out_1.json、data_out_2.json 等。
以下是实现此功能的 Python 代码:
import json
# 读取 JSON 文件
with open("data.json", "r") as f_in:
data = json.load(f_in)
# 遍历 JSON 对象数组,并将每个对象写入单独的文件
for i, d in enumerate(data, 1):
with open(f"data_out_{i}.json", "w") as f_out:
json.dump(d, f_out, indent=4)代码解释:
立即学习“Python免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
如果 JSON 数据不是存储在文件中,而是存储在一个字符串变量中,例如 json_output,则可以使用 json.loads() 函数将字符串解析为 Python 对象。
import json
json_output = """\
[
{"any": 2023},
{
"dia": 24,
"mes": 1,
"any": 2023,
"mes_referencia": 12,
"any_referencia": 2022,
"calendari_nom": "CCC"
},
{
"dia": 4,
"mes": 12,
"any": 2023,
"mes_referencia": 10,
"any_referencia": 2023,
"calendari_nom": "FFF"
},
{
"dia": 4,
"mes": 1,
"any": 2023,
"mes_referencia": 0,
"any_referencia": 2022,
"calendari_nom": "GAS",
"periode_ref": "TT"
},
{
"dia": 3,
"mes": 10,
"any": 2023,
"mes_referencia": 0,
"any_referencia": 2023,
"calendari_nom": "GAS",
"periode_ref": "22"
}
]"""
data = json.loads(json_output)
for i, d in enumerate(data, 1):
with open(f"data_out_{i}.json", "w") as f_out:
json.dump(d, f_out, indent=4)代码解释:
立即学习“Python免费学习笔记(深入)”;
本文介绍了使用 Python 将 JSON 文件分割成多个文件的两种方法:一种是从文件中读取 JSON 数据,另一种是从 JSON 字符串中读取数据。 通过 json 模块的 load、loads 和 dump 函数,可以轻松实现 JSON 数据的读取、解析和写入,从而实现数据的分割和管理。 在实际应用中,需要根据具体情况选择合适的方法,并注意文件路径、JSON 格式和编码问题。
以上就是使用 Python 将 JSON 文件分割成多个文件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号