使用Python导出JSON中的dictionnary

2024-03-28 12:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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文件(保留双引号)?你知道吗


Tags: 文件方法txt数据库jsonwithplacecontent
2条回答

通过使用str()转换对象,生成了Python语法;Python字符串可以使用单引号或双引号。要生成JSON字符串,请使用^{}

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)

问题在于:

file.write(str(dico))  #save my new JSON file

改用json.dumps

file.write(json.dumps(dico))  #save my new JSON file

相关问题 更多 >