'How to get rid of extra curly braces in JSON?
I'm basically creating a contact book, and I want to do it storing data on JSON to practice it. I have sort a code that allows it from a dictionary, but the problem is that when I rerun the script, another dictionary is appended into the existing one, creating a couple of extra braces which throws the error "End of file expected."
This is the code:
import json
new_contacts = {}
def contacts():
while True:
name = input("Contact's name: ")
email = input("Email: ")
number = input("Phone number: ")
new_contacts[name] = {"email": email, "number": number}
"""cursor.execute(
'INSERT INTO contacts VALUES (?, ?, ?)',
(name, email, number)
)"""
restart_or_not = input("Continue? y/n ").lower()
if restart_or_not == "y":
print(new_contacts)
continue
else:
with open('contact_book.json', 'a') as file:
json.dump(new_contacts, file, indent=4)
break
contacts()
And this is a sample of a JSON that comes out from it:
{
"d": {
"email": "e",
"number": "3"
},
"h": {
"email": "y",
"number": "6"
},
"f": {
"email": "r",
"number": "3"
},
"n": {
"email": "j",
"number": "9"
}
}{
"g": {
"email": "j",
"number": "0"
}
}
The first four entries don't create any problem because they are appended in the same run, but if I quit the program and rerun it (example "g") then the new dictionary creates the conflict. Any tips?
Solution 1:[1]
Just updated a bit of the else part of your code. It checks whether a file exists or not. If it exists, the contents of the file is read and updated and then dumped into the file. If it doesn't exist, your old code will be executing.
if os.stat("contact_book.json").st_size != 0:
with open('contact_book.json', 'r+') as file:
contents = json.loads(file.read())
contents.update(new_contacts)
file.seek(0)
json.dump(contents, file, indent=4)
else:
with open('contact_book.json', 'a') as file:
json.dump(new_contacts, file, indent=4)
break
Honestly, not an efficient solution. But this should be able to invoke an idea.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Keerthi Raajan |
