0

I have a dictionary which I update every time the code runs with a user-created username and password. Whenever I run the script the updated keys and values successfully appear on a JSON file. The problem is that the new dictionary values and keys replace the contents of the JSON file instead of being added to them.

my_dict = {}

# there's code here that utilizes the update method for dictionaries to populate #my_dict with a key and value. Due to its length, I'm not posting it. 

with open('data.json', 'r') as f:
    json_string = json.dumps(my_dict)
    json_string


with open('data.json', 'r') as f:
    json.loads(json_string)


with open('data.json', 'w') as f:
    f.write(json_string)

#these successfully write and save the data to the data.json file. When I run #the script again, however, the new data replaces the old data in my_dict. I #want the new my_dict data to be added instead. How do I do this?
ashton
  • 57
  • 10
  • Are you sure you want that? The file will no longer be valid JSON if you have multiple concatenated objects in it. You'll have to jump through more hoops to read it in again. – glibdud May 18 '18 at 19:46
  • Do you need an array of objects? – Kirill Korolev May 18 '18 at 19:47
  • what I need is to be able to loop through my_dict and grab values from the my_dict entries that are stored in data.json – ashton May 18 '18 at 20:01

2 Answers2

0

Use the append status when writing to your file like:

with open('data.json', 'a') as f:
    f.write(json_string)

This will append the string instead of replacing the file entirely.

jmkmay
  • 1,441
  • 11
  • 21
0

If you need to update your JSON file just for saving the same dictionary each time, I think your code works fine.

But if you need to have a JSON array, I'd insert "[]" at the beginning. Then at each iteration you can delete the last character of a file, insert comma and serialize that dict. That makes your JSON file a valid one.

Maybe you considered this case?

import os
import json

my_dict = {}
file_name = "data.json"


def update_dict():
    #update your dictionary here
    my_dict["..."] = ...


if __name__ == "__main__":
    with open(file_name, 'wb+') as file:
        file.write('[]'.encode('utf-8'))

        i = 0

        #do it N times just for testing

        while i < 10:
            update_dict()
            file.seek(-1, os.SEEK_END)
            file.truncate()
            json_str = json.dumps(my_dict)
            file.write(json_str.encode('utf-8'))
            file.write(',]'.encode('utf-8'))
            i += 1

        file.seek(-2, os.SEEK_END)
        file.truncate()
        file.write(']'.encode('utf-8'))
        file.close()
Kirill Korolev
  • 966
  • 3
  • 9
  • 22
  • jmkmay's answer was helpful. I now need a way to turn the concantated objects into valid json code so that I can iterate through them(I am completely new to this so please let me know if this isn't even possible). What exactly do you mean by "[]" at the beginning? Can you show me this in the context of the code? Thanks! – ashton May 18 '18 at 20:05
  • @george I've added a context you've requested – Kirill Korolev May 18 '18 at 20:25