2

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
4
  • 3
    Do you want to open the file in 'a'ppend mode and write more data to it? But then you'll not end up with a valid JSON file. Commented Aug 8, 2015 at 13:36
  • what do you mean the latest and not all of them? Is your snippet inside a for loop in your actual code? Commented Aug 8, 2015 at 13:43
  • Your code snippet is a bit confusing. From the return statement I guess it's part of a function that you're calling in a loop. Commented Aug 8, 2015 at 14:04
  • In future, please try to post a minimal reproducible example. An MCVE makes it a lot easier for people to understand exactly what your problem is, and it also makes it easier for them to write a useful answer, since they can simply edit & test the code you supply. Commented Aug 8, 2015 at 14:24

1 Answer 1

2

You can collect all of your dicts 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"
    }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.