将大型JSON对象分离成许多不同的文件



我有一个JSON文件,文件中有10000个数据项,如下所示。

{
"1":{
"name":"0",
"description":"",
"image":""
},
"2":{
"name":"1",
"description":"",
"image":""
},
...
}

我需要将这个对象中的每个条目写入到它自己的文件中。

例如,每个文件的输出如下所示:

1.json

{
"name": "",
"description": "",
"image": ""
}

我有以下代码,但我不确定如何从这里开始。有人能帮忙吗?

import json

with open('sample.json', 'r') as openfile:

# Reading from json file
json_object = json.load(openfile)

您可以使用for循环来迭代外部对象中的所有字段,然后为每个内部对象创建一个新文件:

import json
with open('sample.json', 'r') as input_file:
json_object = json.load(input_file)
for key, value in json_object.items():
with open(f'{key}.json', 'w') as output_file:
json.dump(value, output_file)

最新更新