我有一个JSON文件(存储在database.txt中)我想在方法addEvent()中使用python字典进行修改:
def addEvent(eventName, start, end, place):
newdict={} #make a new dictionnary
newdict["NAME"]=eventName
newdict["START"]=start
newdict["END"]=end
newdict["place"]=place
try:
with open("database.txt",'r') as file:
content=file.read()
dict=json.loads(content) #make dictionnary with original JSON file
liste.append(newdict)
dico["event"]=liste #combine 2dictionnaries
with open("database.txt", 'w') as file:
file.write(str(dico)) #save my new JSON file
except:
...
我的问题: 我只能运行一次这种方法,第二次收到错误信息:
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
addEvent()方法修改我的database.txt文件:它不再引用双引号但是重音,所以我不能再次使用dict=json.loads(content)
我的问题我是否正确保存了我的JSON文件?如何将我的JSON格式保存在我的database.txt文件中(保留双引号)?
答案 0 :(得分:0)
通过使用str()
转换对象,您生成了 Python语法; Python字符串可以使用单引号或双引号。要生成JSON字符串,请使用json.dumps()
:
file.write(json.dumps(dico))
json
模块具有json.loads()
和json.dumps()
的变体,可直接使用文件;没有必要自己读或写,只需使用函数名而不直接在文件对象上s
:
with open("database.txt", 'r') as file:
d = json.load(file)
和
with open("database.txt", 'w') as file:
json.dump(dico, file)
答案 1 :(得分:0)
问题在于:
file.write(str(dico)) #save my new JSON file
改为使用json.dumps:
file.write(json.dumps(dico)) #save my new JSON file