YYC_Code
YYC_Code

Reputation: 45

python and appending to JSON file

I have a tabbed window that I ask users to input some data, then press a button that updates both a list view and appends the new data to the end of a JSON file, but I can't seem to figure out how to append the data within the square [ ] brackets to make it valid JSON, so what I want is:

[
    {
        "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."
    }
]

Which validates as correct JSON format, but what I get when appending to the file is:

[
    {
        "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."
    }
]

Which because of the [ ] brackets is enclosing each appended item, it is no longer valid JSON. So how can I append the items between the [ and ] in order to keep the JSON valid? Is there a way to maybe append the items, then go to the beginning of the file and insert the [, then move to the end of the file and append ]?

The problem is, the user can add groceries to the JSON file anytime they want as I am technically using the JSON as a 'database'. When the user runs the program, I want to be able to re-read in the JSON data and populate the list control with the previous entries.

Or should I look at a different method of storing the data?

Thanks!

Upvotes: 1

Views: 212

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113950

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)

or better yet abstract it out

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()

Upvotes: 1

Related Questions