data_garden data_garden - 27 days ago 9
JSON Question

Python - create one list for many json files

I am looking up a folder in order to print all

json
files in one go:

path_to_json = 'playlists/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]

for js in json_files:
with open(os.path.join(path_to_json, js)) as json_file:
playlists = json.load(json_file)
print playlists


the code prints me this:

{
"user1": {
"Make You Feel My Love": 1.0,
"I See Fire": 1.0,
"High And Dry": 1.0,
"Fake Plastic Trees": 1.0,
"One": 1.0,
"Goodbye My Lover": 1.0,
"No Surprises": 1.0
}
}
{
"user2": {
"Codex": 1.0,
"No Surprises": 1.0,
"O": 1.0,
"Go It Alone": 1.0
}
}
{
"user3": {
"Fake Plastic Trees": 1.0,
"High And Dry": 1.0,
"No Surprises": 1.0
}
}
{
"user4": {
"No Distance Left To Run": 1.0,
"Running Up That Hill": 1.0,
"Fake Plastic Trees": 1.0,
"The Numbers": 1.0,
"No Surprises": 1.0
}
}
{
"user5": {
"Wild Wood": 1.0,
"You Do Something To Me": 1.0,
"Reprise": 1.0
}
}


how do I change the code so I can end up with a
list
containing all of the above
dictionaries
?

Answer

Simply create a list and append each of the dictionary objects to the list at each iteration of the for:

lst = []
for js in json_files:
    with open(os.path.join(path_to_json, js)) as json_file:
        playlists = json.load(json_file)
        lst.append(playlists)
Comments