Python 3.5
您好,我有以下代码用于向JSON数据中添加元素:
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()
但这会产生结果:
第一组数据
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}
编辑后的数据
{"chat_text": [{"a": "b", "c": "d", "e": "f"}]}{"chat_text": [{'x':'x'},{"a": "b", "c": "d", "e": "f"}]}
所以我写了这段代码:
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"}]}
编辑后的数据
{"chat_text": [{"x","x"},{"a": "b", "c": "d", "e": "f"}]}
正如您所看到的,它用空格替换了第一个数据,我希望它是什么都没有...有任何想法吗?
char_text
后将 JSON 加载到文件中即可。 - Andriy IvaneykojsonFile.seek(0); json.dump(jdata, jsonFile)
- Aran-Fey