Writing to a JSON file and updating said file
<p>I have the following code that will write to a JSON file:</p>

<pre><code>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))
</code></pre>

<p>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?</p>

<p>As of right now when I run the code I get the following:</p>

<pre><code>write_data_to_table("test1", "0123456789")
write_data_to_table("test2", "00123456789")
write_data_to_table("test3", "000123456789")

#&lt;= {"test1": "0123456789"}{"test2": "00123456789"}{"test3": "000123456789"}
</code></pre>

<p>How can I update the file without completely screwing with it?</p>

<p>My expected output would probably be something along the lines of:</p>

<pre><code>{
  "test1": "0123456789",
  "test2": "00123456789",
  "test3": "000123456789",
}
</code></pre>

<p>You may read the JSON data with :</p>

<pre><code>parsed_json = json.loads(json_string)
</code></pre>

<p>You now manipulate a classic dictionary. You can add data with :</p>

<pre><code>parsed_json.update({'test4': 0000123456789})
</code></pre>

<p>Then you can write data to a file using :</p>

<pre><code>with open('data.txt', 'w') as outfile:
    json.dump(parsed_json, outfile)
</code></pre>

python json python-2.7