1

I want to make a function that recives a data in a type of dictionary, and then appends that data to JSON file. This is how JSON file to looks like [{},{},{}] and after appending I want it to be [{},{},{},{}]. Function below is what I tried, if I use 'w', it overwrites, and if I use 'a', file after appending looks like this [{},{},{}{}] which isn't JSON anymore. How to achieve this?

    def save_to_file(user_data):
        f = open('users.json', 'a')
        json.dump(user_data, f, indent=2)
        f.close()

3 Answers 3

3

This is one approach.

Ex:

def save_to_file(user_data):
    with open('users.json') as jfile:
        data = json.loads(jfile)             #Read content
    data.append(user_data)                   #Append 
    with open('users.json', 'w') as jfile:
        json.dump(data, jfile, indent=2)     #Write back
Sign up to request clarification or add additional context in comments.

1 Comment

So I have to get array of dictionaries from JSON file, then append to that array, then whole array to save in JSON file? It can't be done by appending just one user to the file directly?
0

Check the following code: It works:

import json
user_data = {"a":123}
def save_to_file(user_data):
    f = open("tweet.json", 'a')
    json.dump(user_data, f)
    f.close()
save_to_file(user_data)

1 Comment

no issue is still the same, after second appending JSON file looks like {}{} and it should be like {},{}
0

Rather than writing your own logic perhaps use TinyDB. It uses JSON to save data and makes it rather easy to append/delete data even from multiple sources: https://tinydb.readthedocs.io/en/latest/index.html

1 Comment

You could also load the JSON and put it into a variable and keep it while you have your script running and when a new dictionary item is needed to append you append it to the variable you have and overwrite your json with the variable. I would not recommend this tho.

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.