feltspar
feltspar

Reputation: 324

Reading ALL objects into a list from a JSON file in Python

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.

Upvotes: 2

Views: 13169

Answers (2)

poke
poke

Reputation: 387557

data.append(json.loads(f))

This appends the list you read from the JSON file as a single element to the list. So after your other append, the list will have two elements: One list of songs, and that one song object you added afterwards.

You should use list.extend to extend the list with the items from another list:

data.extends(json.loads(f))

Since your list is empty before that, you can also just load the list from the JSON and then append to that one:

data = json.loads(f)
data.append(vars(songObj))

Upvotes: 0

Jenos
Jenos

Reputation: 171

I think you have a couple issues going on here. First, valid JSON doesn't use single quotes ('), it is all double quotes ("). You are looking for something like:

[{
"id":123,
"emotions":[],
"lyrics":"AbC",
"emotionID":0,
"artist":"222",
"sentimentScore":0,
"subjects":[],
"synonymKeyWords":[],
"keyWords":[]
},

{
"id":123,
"emotions":[],
"lyrics":"EFG",
"emotionID":0,
"artist":"223",
"sentimentScore":0,
"subjects":[],
"synonymKeyWords":[],
"keyWords":[]
}
]

Secondly, you need to open the json file for reading and then load it as json. The following should work for you:

with open(read_file) as file:
  data = json.load(file)

with open(write_file, 'w') as file:
  json.dump(data, file)

print(data)

Upvotes: 2

Related Questions