Reputation: 31
i am currently having problem saving one combined json file in my python code but what it does it one saves the latest "result" in json file and not all of them so i had to save all the different results in seperate json file but instead i want to store it in single faculty.json file, how can i do that?
here is my code:
outputPath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')
if os.path.isdir(outputPath) is False:
os.makedirs(outputPath)
result = {'empid': facultyID, 'name': name, 'school': school, 'designation': designation, 'room': room, 'intercom': intercom, 'email': email, 'division': division, 'open_hours': openHours}
with open('output/faculty.json', 'w') as outfile:
json.dump(result, outfile)
return result
Upvotes: 2
Views: 89
Reputation: 55469
You can collect all of your dict
s into a list, and then save that list as a JSON file. Here's a simple demo of the process. This program re-loads the JSON file to verify that it's legal JSON and that it contains what we expect it to.
import json
#Build a simple list of dicts
s = 'abcdefg'
data = []
for i, c in enumerate(s, 1):
d = dict(name=c, number=i)
data.append(d)
fname = 'data.json'
#Save data
with open(fname, 'w') as f:
json.dump(data, f, indent=4)
#Reload data
with open(fname, 'r') as f:
newdata = json.load(f)
#Show all the data we just read in
print(json.dumps(newdata, indent=4))
output
[
{
"number": 1,
"name": "a"
},
{
"number": 2,
"name": "b"
},
{
"number": 3,
"name": "c"
},
{
"number": 4,
"name": "d"
},
{
"number": 5,
"name": "e"
},
{
"number": 6,
"name": "f"
},
{
"number": 7,
"name": "g"
}
]
Upvotes: 2