Pyth0nicPenguin Pyth0nicPenguin - 1 month ago 7
JSON Question

Writing to a JSON file and updating said file

I have the following code that will write to a JSON file:

import json

def write_data_to_table(word, hash):
data = {word: hash}
with open("rainbow_table\\rainbow.json", "a+") as table:
table.write(json.dumps(data))


What I want to do is open the JSON file, add another line to it, and close it. How can I do this without messing with the file?

As of right now when I run the code I get the following:

write_data_to_table("test1", "0123456789")
write_data_to_table("test2", "00123456789")
write_data_to_table("test3", "000123456789")

#<= {"test1": "0123456789"}{"test2": "00123456789"}{"test3": "000123456789"}


How can I update the file without completely screwing with it?

My expected output would probably be something along the lines of:

{
"test1": "0123456789",
"test2": "00123456789",
"test3": "000123456789",
}

Answer

You may read the JSON data with :

parsed_json = json.loads(json_string)

You now manipulate a classic dictionary. You can add data with :

parsed_json.update({'test4': 0000123456789})

Then you can write data to a file using :

with open('data.txt', 'w') as outfile:
    json.dump(parsed_json, outfile)