我有數十萬個帶有注釋資訊的 json 檔案。示例 json 檔案:
{
"version": "4.5.4",
"flags": {
"flag1": false,
"surface": false,
"gtype": false,
"light": false
},
"shapes": [
{
"label": "object-1",
"points": [
[
100.5,
105.65423
]
],
"group_id": null,
"shape_type": "point",
"flags": {}
},
{
"label": "assembly",
"points": [
[
31.8416,
52.546
],
[
65,
97
]
],
"group_id": null,
"shape_type": "rectangle",
"flags": {}
}
],
"location": "/data/abc.bmp",
"Data": null,
"Height": 540,
"Width": 960
}
我想在 json 檔案的末尾添加元素。比如說,元素名稱是路徑,它是一個字串,那么我想要的輸出應該是這樣的,
... existing data in json ...
... existing data in json ...
"location": "/data/abc.bmp",
"Data": null,
"Height": 540,
"Width": 960,
"path": "/data/pqr.pgm"
}
我有 python 代碼,它確實向 json 檔案添加了元素,但它重新排列了檔案的內容。以下是我的代碼如何讀取 json
with open(jsonFileName,"r") as jsonFile:
jsonData = json.loads(jsonFile.read())
以下是我如何向檔案中添加新元素
jsonData['path'] = pathValueString
with open(jsonFileName, "w") as outputJsonFile:
outputJsonFile.seek(0,2)
json.dump(jsonData, outputJsonFile, indent=4)
Python版本:3.4.10
uj5u.com熱心網友回復:
在 Python 3.6 之前,標準dicts 是無序的,這意味著無法保證加載 json 并保存鍵的順序保持不變。有使用from collections import OrderedDict的可能性,但當然讓它作業json.loads并不是微不足道的。
從 3.7 開始,dict物件保證保持插入順序,因此您可以使用它來保持原始檔案中的順序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467328.html
上一篇:使用繼承Codable的回傳類進行列舉以將JSON決議為您的模型類
下一篇:將檔案從S3下載到用戶計算機
