mzage mzage - 1 year ago 40
JSON Question

how to empty json file before dumping data into it

python 3.5

hi i have following codes to add an element to json data :

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()


but it would be result:

first data

{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}


edited data

{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}{"chat_text": [{'x':'x'},{"a": "b", "c": "d", "e": "f"}]}


so i wrote this 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()


result would be this :

first data

{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}


edited data

{"chat_text": [{"x","x"},{"a": "b", "c": "d", "e": "f"}]}


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

any ideas?

Answer Source

the issue is essentially that you are opening the file twice in different modes.

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()

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.