简体   繁体   中英

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():

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

My question Did I correctly save my JSON file ? How can I keep my JSON format in my database.txt file (keep double quotes) ?

You produced Python syntax by converting the object with str() ; Python strings can use either single or double quotes. To produce a JSON string, use json.dumps() :

file.write(json.dumps(dico))

The json module has variants of json.loads() and json.dumps() that work directly with files; there is no need to read or write yourself, just use the function names without the trailing s on file objects directly:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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