how to empty json file before dumping data into it
<p><strong>python 3.5</strong></p>

<p>hi i have following codes to add an element to json data :</p>

<pre><code>jsonFile = open("json.json", mode="r+", encoding='utf-8')
jdata = json.load(jsonFile)
jdata['chat_text'].insert(0, {'x':'x'})
json.dump(jdata, jsonFile)
jsonFile.close()
</code></pre>

<p>but it would be result:</p>

<p><strong>first data</strong></p>

<pre><code>{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
</code></pre>

<p><strong>edited data</strong></p>

<pre><code>{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}{"chat_text": [{'x':'x'},{"a": "b", "c": "d", "e": "f"}]}
</code></pre>

<p>so i wrote this code :</p>

<pre><code>jsonFile = open("json.json", mode="r+", encoding='utf-8')
jdata = json.load(jsonFile)
jdata['chat_text'].insert(0, {'x':'x'})
open('json.json', mode='w').close() #deleting first data
json.dump(jdata, jsonFile)
jsonFile.close()
</code></pre>

<p>result would be this :</p>

<p><strong>first data</strong></p>

<pre><code>{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
</code></pre>

<p><strong>edited data</strong></p>

<pre><code>                                               {"chat_text": [{"x","x"},{"a": "b", "c": "d", "e": "f"}]}
</code></pre>

<p>as you can see it replaces first data with space and i want it to be nothing...</p>

<p>any ideas?</p>

<p>the issue is essentially that you are opening the file twice in different modes.</p>

<pre><code>jsonFile = open("json.json", mode="r")
jdata = json.load(jsonFile)
jsonFile.close()
jdata['chat_text'].insert(0, {'x':'x'})
jsonFile = open('json.json', mode='w+')
json.dump(jdata, jsonFile)
jsonFile.close()
</code></pre>

<p>So the first 3 lines open your file and load it into jdata, then close that file.
Do whatever manipulation you need
Open the file again, for writing this time. Dump data, close file.</p>

python json