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>If you are sure the closing "}" is the last byte in the file you can do this:</p>

<pre><code>&gt;&gt;&gt; f = open('test.json', 'a+')
&gt;&gt;&gt; json.dump({"foo": "bar"}, f)  # create the file
&gt;&gt;&gt; f.seek(0)
&gt;&gt;&gt; f.read()
'{"foo": "bar"}'
&gt;&gt;&gt; f.seek(-1, 2)
&gt;&gt;&gt; f.write(',\n', f.write(',\n' + json.dumps({"spam": "bacon"})[1:]))
&gt;&gt;&gt; f.seek(0)
&gt;&gt;&gt; print(f.read())
{"foo": "bar",
"spam": "bacon"}
</code></pre>

<p>Since your data is not hierarchical, you should consider a flat format like "TSV".</p>

python json python-2.7