使用Python将JSON文件拆分为多个文件(notebook)[已关闭]

yhuiod9q  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(81)

**已关闭。**此问题为not reproducible or was caused by typos。目前不接受回答。

这个问题是由错字或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
27天前关闭。
Improve this question
我使用的是Python(notebook),我有一个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)


你能给予我一个怎么做的主意吗?
谢谢.

w8biq8rn

w8biq8rn1#

以下是如何从提供的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)

相关问题