I am getting myself familiar with Classes/OOP in Python and I am practicing on a basic program for tracking finances. I have the program to the point where I add entries to a JSON file and save that file away. Now I want to read in the JSON file into a dataframe and perform some aggregates on it. That's where I am stuck. The following fails with:
json.decoder.JSONDecodeError: Extra data: line 7 column 2 (char 122)
The JSON file looks like this:
{
"DATE": "2019-02-01 12:57:13.140724",
"HSA": "600",
"401K": "90",
"ROTH": "900",
"SAVINGS": "1000"
}{
"DATE": "2019-02-01 12:57:26.995724",
"HSA": "250",
"401K": "90",
"ROTH": "80",
"SAVINGS": "900"
}
Any ideas?
import datetime
import json
import pandas as pd
class BankAccount:
def __init__(self):
self.accounts = ['HSA', '401K', 'ROTH', 'SAVINGS']
self.records = {}
self.now = datetime.datetime.now()
def data_entry(self):
for i in self.accounts:
x = input('Enter the amount for {}:'.format(i))
self.records['DATE'] = self.now
self.records[i] = x
def display(self):
return self.records
def savefile(self):
with open('finance.json', 'a') as file:
file.write(json.dumps(self.records, indent=4, sort_keys=True, default=str))
file.close()
def analyzedata(self):
with open('finance.json', 'r') as f:
obj = json.load(f)
frame = pd.DataFrame(obj, columns=['401K', 'HSA', 'ROTH', 'SAVINGS', 'DATE'])
print(frame)
s = BankAccount()
s.data_entry()
s.savefile()
s.analyzedata()
BTW feel free to offer any other suggestions as to why this is a bad way to do it, i.e. using a Dictionary or whatever it may be. Still learning. Thanks
lines=True__init__if there is data in the file then fillrecordswith that data before you alter it. then use 'w' as your file option when you save it. This will result in a correct json file format and a sort of persistence to the object.