I may be doing multiple things wrong here. Very new to python and JSON. I have multiple "song"-JSON objects. Which I need to write and read from a file. The JSON File looks like this (basically a list of song objects, NOT one per line! here only two):
[{
"emotions": [],
"lyrics": "2222",
"emotionID": 0,
"artist": "22453232",
"sentimentScore": 0,
"subjects": [],
"synonymKeyWords": [],
"keyWords": []
}, {
"emotions": [],
"lyrics": "244422",
"emotionID": 0,
"artist": "2121222",
"sentimentScore": 0,
"subjects": [],
"synonymKeyWords": [],
"keyWords": []
}]
I want to read the song objects into a list so that I can append another song object and then write it back. What I have is obviously wrong. Help please.
import json
from song import Song
def writeToFile():
lyrics = input( "enter lyrics: " )
artist = input("enter artist name: ")
songObj = Song(lyrics, artist)
print(vars(songObj))
data = []
with open('testWrite.json') as file:
data = json.load(file)
data.append(vars(songObj))
print(data)
with open('testWrite.json', 'w') as file:
json.dump(data, file)
ctr = "y"
while (ctr=="y"):
writeToFile()
ctr = input("continue? y/n?")
Open to other suggestions as well, if I can avoid loading all the objects for every time I want to append a new song object.