【问题标题】:Export dictionnary in JSON using Python使用 Python 以 JSON 格式导出字典
【发布时间】:2015-12-05 18:11:15
【问题描述】:

我有一个 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 文件?如何在我的 database.txt 文件中保留 JSON 格式(保留双引号)?

【问题讨论】:

    标签: python json python-3.x dictionary


    【解决方案1】:

    您通过使用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)
    

    【讨论】:

    • 谢谢你帮助我了解更多关于 JSON 文件的知识
    【解决方案2】:

    问题出在这里:

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

    改用json.dumps

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多