我需要检查一个.json
文件是否在所有列表中都有"quantity": float
属性,并将该属性添加到没有单独属性的地方,但我不知道如何这样做(我没有使用JSON格式的经验)
我试过.append
和.insert
函数,但没有一个像我需要的那样工作
我有这样一个清单:
{
"id": 9746439,
"name": "Home Theater LG com blu-ray 3D, 5.1 canais e 1000W",
"quantity": 80,
"price": 2199.0,
"category": "Eletrônicos"
},
{
"id": 2162952,
"name": "Kit Gamer acer - Notebook + Headset + Mouse",
"price": 25599.0,
"category": "Eletrônicos"
},
如您所见,第二部分没有“quantity”属性,我需要像"quantity": 0
那样添加它,但不知道如何添加。这种情况在我的列表中出现过多次,我想知道如何编写一个代码来查找这些错误,并像列表的其他部分一样在“name”和“price”之间添加属性
您可以简单地分配属性并将其安全地保存到一个文件或以后需要它的任何地方
最简单的方法可能是将json文件加载到带有
json.load()
的Python数据结构中,然后在缺少的地方插入quantity
项,然后将其写入新的json文件前几天我遇到了同样的难题,并用下面的代码解决了它。我完全接受这可能是“懒惰”的方式做它,但它是超级容易阅读
我在这里使用的方法是Try and Except,让我们尝试选择数据中的quantity键,嘿,如果没有,让我们添加它
让我知道你怎么用这个方法
相关问题 更多 >
编程相关推荐