我有一個包含 10000 個資料條目的 JSON 檔案,如下所示。
{
"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)
uj5u.com熱心網友回復:
您可以使用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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/446386.html
