【发布时间】:2022-01-18 03:23:05
【问题描述】:
我对编程很陌生,所以请原谅任何可怕的解释。基本上我有 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' 对象没有属性 'append'
【问题讨论】:
-
包括您尝试过的代码和任何错误
-
这不是一个有效的 JSON 文件。周围必须有
{ }。 -
你不应该使用
append。只是object['collection'] = {'name': collection_name}其中object是您从json.load获得的对象 -
我知道,它只是json文件的一部分。
-
如您所见,
collection不在properties对象内。