我對編程很陌生,所以請原諒任何可怕的解釋。基本上我有 1000 個 json 檔案,所有這些檔案都需要在末尾添加相同的文本。這是一個例子:
這就是它現在的樣子:
{"properties": {
"files": [
{
"uri": "image.png",
"type": "image/png"
}
],
"category": "image",
"creators": [
{
"address": "wallet address",
"share": 100
}
]
}
}
我想看起來像這樣:
{"properties": {
"files": [
{
"uri": "image.png",
"type": "image/png"
}
],
"category": "image",
"creators": [
{
"address": "wallet address",
"share": 100
}
]
},
"collection": {"name": "collection name"}
}
我已經盡力使用追加和更新,但它總是告訴我沒有要追加的屬性。我也不知道自己在做什么。
這會很尷尬,但這是我嘗試過但失敗的方法。
import json
entry= {"collection": {"name": "collection name"}}
for i in range((5)):
a_file = open("./testjsons/" str(i) ".json","r")
json_obj = json.load(a_file)
print(json_obj)
json_obj["properties"].append(entry)
a_file = open(str(i) ".json","w")
json.dump(json_obj,a_file,indent=4)
a_file.close()
json.dump(a_file, f)
錯誤代碼:json_obj["properties"].append(entry) AttributeError: 'dict' object has no attribute 'append'
uj5u.com熱心網友回復:
你不用append()來添加到字典。您可以分配給鍵以添加單個條目,或用于.update()合并字典。
import json
entry= {"collection": {"name": "collection name"}}
for i in range((5)):
with open("./testjsons/" str(i) ".json","r") as a_file:
a_file = open("./testjsons/" str(i) ".json","r")
json_obj = json.load(a_file)
print(json_obj)
json_obj["properties"].update(entry)
with open(str(i) ".json","w") as a_file:
json.dump(json_obj,a_file,indent=4)
uj5u.com熱心網友回復:
JSON 與 XML 一樣,是一種專門的資料格式。您應該始終決議資料并盡可能將其作為 JSON 使用。這與您將“添加到末尾”或“附加”文本的純文本檔案不同。
Python 中有許多 json 決議庫,但您可能希望使用標準 Python 庫中內置的json編碼器。對于檔案myfile.json,您可以:
import json
with open('myfile.json`, 'r') as f:
myfile = json.load(f) # read the file into a Python dict
myfile["collection"] = {"name": "collection name"} # here you're adding the "collection" field to the end of the Python dict
# If you want to add "collection" inside "properties", you'd do something like
#. myfile["properties"]["collection"] = {"name": "collection name"}
with open('myfile.json', 'w') as f:
json.dump(myfile, f) # save the modified dict into the json file
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414035.html
標籤:
