我正在使用Python(笔记本) 我有一个 JSON 文件,该结构存储在 json_out var 中:
[
{"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"
}
]
我需要将文件拆分为多个文件,每个文件对应每个 { } 块。我对如何做到这一点有点困惑。我已经尝试过,但它对我不起作用:
import json
with (json_out, 'r') as f_in:
data = json.load(f_in)
for i, fact in enumerate(data[], 1):
with open('data_out_{}.json'.format(i), 'w') as f_out:
d = {}
json.dump(d, f_out, indent=4)
你能告诉我如何做吗?
谢谢。
以下是如何从提供的 Json 文件创建文件的示例:
import json
with open("data.json", "r") as f_in:
data = json.load(f_in)
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)
例如
data_out_2.json
将包含:
{
"dia": 24,
"mes": 1,
"any": 2023,
"mes_referencia": 12,
"any_referencia": 2022,
"calendari_nom": "CCC"
}
编辑:如果
json_output
包含带有 JSON 编码数据的字符串:
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)