我有一个JSON文件(存储在数据库.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()方法修改我的数据库.txt文件:它不再包含双引号,而是重音符号,所以我不能再次使用dict=json.loads(content)
我的问题我是否正确保存了JSON文件?如何将JSON格式保存在数据库.txt文件(保留双引号)?你知道吗
通过使用} :
str()
转换对象,生成了Python语法;Python字符串可以使用单引号或双引号。要生成JSON字符串,请使用^{json
模块有json.loads()
和json.dumps()
的变体,可以直接处理文件;不需要自己读写,只需直接在文件对象上使用函数名,而不使用后面的s
:以及
问题在于:
改用json.dumps:
相关问题 更多 >
编程相关推荐