Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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)

Solution 2:

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

Post a Comment for "Reading All Objects Into A List From A Json File In Python"