我正在基于图像制作一个json文件,在该json文件中,它需要图片中所有面板的信息。因为面板数量总是不同的,所以我需要在for循环中将面板信息附加到json中,并带有图片中面板数量的范围,但是当我这样做时,它仅显示json文件中的最后一个附件。>
现在,我正在使用2个字典,其中1个总是需要使用的基本json布局,另一个使用在面板的for循环中。我在for循环中使用export class GridManager {
changeBackground() {
var x = Math.floor(Math.random() * document.querySelectorAll(".grid-item").length);
if (this.items[x].backgroundImage != "" && this.items[x].backgroundImage != null) {
document.querySelector(".container").style.backgroundImage = `url('${this.items[x].backgroundImage}')`;
}
}
}
,但这会在每个周期覆盖其自身
dict.update(paneldict)
在这种情况下,我有一个范围为2的for循环,因此我在json中应该有2个面板:panel0和panel1,但是实际输出是这个
appDict = {
'type': 'setOfInformationpoints',
'version': '0.1',
'informationpoints': [{
'key': 'worktop01',
'datatype': 'productmodel:worktop',
'value': {
'type': 'productmodel',
'version': '1.2',
'globalmeasurments':{
'distx': 2777,
'disty': 1900,
'distz': 60
},
"panels": [{
}]
}
}]
}
def makepanel(index):
panel = {"id": "panel{}".format(index),
"measurements": {
"distx": 2177,
"disty": 600,
"distz": 60
},
"orientation": "north",
"position": {
"x":0,
"y":0
}
}
return panel
for panels in range(2):
panel = makepanel(panels)
panel1 = panel.copy()
appDict.update(panel)
print(panels)
with open('data.json', 'w', encoding='utf-8') as outfile:
json.dump(appDict, outfile, ensure_ascii=False, indent=4)
我希望它像这样:
{
"type": "setOfInformationpoints",
"version": "0.1",
"informationpoints": [
{
"key": "worktop01",
"datatype": "productmodel:worktop",
"value": {
"type": "productmodel",
"version": "1.2",
"globalmeasurments": {
"distx": 2777,
"disty": 1900,
"distz": 60
},
"panels": [
{}
]
}
}
],
"id": "panel1",
"measurements": {
"distx": 2177,
"disty": 600,
"distz": 60
},
"orientation": "north",
"position": {
"x": 0,
"y": 0
}
}
不要紧缩缩进,直到我让它起作用为止。
答案 0 :(得分:3)
如果要保留许多面板,则必须将其保留在列表中
[ {"id": "panel0", ... }, {"id": "panel1", ...} ]
或对每个面板使用uniqe键。 id
中的值可能是键-"panel0"
,"panel1"
等。
{ "panel0":{"id": "panel0", ... }, "panel1":{"id": "panel1", ...} ]
答案 1 :(得分:2)
如果我理解的正确,您想将第二个词典合并到第一个词典中,而不会覆盖现有的子条目。可能可以使用Dictionaries of dictionaries merge中所述的递归字典合并策略来解决您的问题。
答案 2 :(得分:0)
最好将字典视为一组键:值对,要求键是唯一的(在一个字典中)