简体   繁体   English

使用Python在JSON中导出字典

[英]Export dictionnary in JSON using Python

I have a JSON file (stored in database.txt) I want to modify using python dictionary in method addEvent(): 我有一个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:
    ...

My problem: I can run this method only one time, second time I receive an error message: 我的问题:我只能运行此方法一次,第二次收到错误消息:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

addEvent() method modify my database.txt file: it doesn't incule double quotes anymore but accents so i can't use dict=json.loads(content) second time addEvent()方法修改我的database.txt文件:它不再包含双引号,而是带有重音,因此我第二次不能使用dict=json.loads(content)

My question Did I correctly save my JSON file ? 我的问题我是否正确保存了JSON文件? How can I keep my JSON format in my database.txt file (keep double quotes) ? 如何将JSON格式保留在database.txt文件中(请保留双引号)?

You produced Python syntax by converting the object with str() ; 您通过使用str()转换对象产生了Python语法 Python strings can use either single or double quotes. Python字符串可以使用单引号或双引号。 To produce a JSON string, use json.dumps() : 要生成JSON字符串,请使用json.dumps()

file.write(json.dumps(dico))

The json module has variants of json.loads() and json.dumps() that work directly with files; json模块具有json.loads()json.dumps()变体,它们可以直接与文件一起使用。 there is no need to read or write yourself, just use the function names without the trailing s on file objects directly: 无需读或写自己,只需使用函数名称,而无需在文件对象上直接添加s即可:

with open("database.txt", 'r') as file:
    d = json.load(file)

and

with open("database.txt", 'w') as file:
    json.dump(dico, file)

The problem is here: 问题在这里:

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

Use json.dumps instead: 请改用json.dumps

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM