我有一个选项卡式窗口,要求用户输入一些数据,然后按一个按钮,该按钮既可以更新列表视图,又可以将新数据追加到JSON文件的末尾,但是我似乎无法弄清楚将数据附加在方括号[]中以使其有效为JSON,所以我想要的是:
[
{
"store": "My Store",
"address": "123 Anywhere Calgary, Ab",
"category": "Grocery",
"item": "Ground Coffee",
"qty": "1",
"price": "10.99",
"GST": false,
"PST": false,
"EHC": "0.",
"deposit": "0.",
"other": "0."
},
{
"store": "My Store",
"address": "123 Anywhere Calgary, Ab",
"category": "Grocery",
"item": "Flour, All Purp",
"qty": "1",
"price": "9.99",
"GST": false,
"PST": false,
"EHC": "0.",
"deposit": "0.",
"other": "0."
},
{
"store": "My Store",
"address": "123 Anywhere Calgary, Ab",
"category": "Grocery",
"item": "Taco Shells",
"qty": "1",
"price": "4.59",
"GST": false,
"PST": false,
"EHC": "0.",
"deposit": "0.",
"other": "0."
},
{
"store": "My Store",
"address": "123 Anywhere Calgary, Ab",
"category": "Grocery",
"item": "BBQ Sauce",
"qty": "1",
"price": "3.79",
"GST": false,
"PST": false,
"EHC": "0.",
"deposit": "0.",
"other": "0."
},
{
"store": "My Store",
"address": "123 Anywhere Calgary, Ab",
"category": "Grocery",
"item": "Ritz Bits",
"qty": "1",
"price": "3.49",
"GST": false,
"PST": false,
"EHC": "0.",
"deposit": "0.",
"other": "0."
}
]
哪个可以验证为正确的JSON格式,但是在附加到文件时得到的是:
[
{
"store": "My Store",
"address": "123 Anywhere Calgary, Ab",
"category": "Grocery",
"item": "Ground Coffee",
"qty": "1",
"price": "10.99",
"GST": false,
"PST": false,
"EHC": "0.",
"deposit": "0.",
"other": "0."
}
]
[
{
"store": "My Store",
"address": "123 Anywhere Calgary, Ab",
"category": "Grocery",
"item": "Flour, All Purp",
"qty": "1",
"price": "9.99",
"GST": false,
"PST": false,
"EHC": "0.",
"deposit": "0.",
"other": "0."
}
]
由于[]括号将每个附加项括起来,因此它不再是有效的JSON。那么,如何在[和]之间附加项目以保持JSON有效?有没有一种方法可以追加项目,然后转到文件的开头并插入[,然后移至文件的末尾并追加]?
问题是,从技术上来说,用户可以将杂货添加到JSON文件中,就像我在技术上使用JSON作为“数据库”一样。当用户运行该程序时,我希望能够重新读取JSON数据并使用以前的条目填充列表控件。
还是应该看看另一种存储数据的方法?
谢谢!
答案 0 :(得分:1)
with open("my_file.json","rb") as f:
existing = json.load(f)
existing.append(item)
with open("my_file.json","wb") as f:
json.dump(existing,f)
或者更好地将其抽象出来
class JSONList(object):
def __init__(self,fname):
self.fname = fname
self.items = []
self.load()
def save():
with open(self.fname,"wb") as f:
json.dump(self.items,f)
def load(self):
try:
self.items = json.load(open(self.fname,"rb"))
except: # bad form empty except... but whatever
self.items = []
def append(self,new_item,save=True):
self.items.append(new_item)
if save:
self.save()