如何去掉 JSON 中多余的花括号?
How to get rid of extra curly braces in JSON?
我基本上是在创建通讯录,我想在 JSON 上存储数据以进行练习。我已经从字典中排序了一个允许它的代码,但问题是当我重新 运行 脚本时,另一个字典被附加到现有的字典中,创建了几个额外的大括号,引发错误“End of预期文件。
这是代码:
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()
这是从中得出的 JSON 的样本:
{
"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"
}
}
前四个条目不会造成任何问题,因为它们附加在同一个 运行 中,但如果我退出程序并重新 运行 它(例如“g”),那么新字典造成冲突。有什么建议吗?
这样做的一种方法是,在添加到文件之前,删除最后一个右括号 }
并在转储之前,将字典转换为字符串并使用此 [=12 删除第一个括号=].
我为您编写的另一种方法是将 json 加载到变量中,添加新输入,然后将其重新转储到文件中
import json
from os import path # it helps to check if file exists
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:
# if the file doesn't exist, write an empty json object into it
# which will make it easier later to load data from
if not path.exists('contact_book.json'):
with open('contact_book.json', 'w+') as file:
json.dump({}, file)
# This loads the data into the variable dict called loaded_data
with open('contact_book.json', 'r') as file:
loaded_data = json.load(file)
for k, v in new_contacts.items():
loaded_data[k] = v
# redumps your data into the json file
with open('contact_book.json', 'w') as file:
json.dump(loaded_data, file, indent=4)
break
contacts()
刚刚更新了您代码的其他部分。它检查 文件是否存在 。如果存在,则读取并更新文件的内容,然后将其转储到文件中。如果它不存在,您的旧代码将被执行。
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
老实说,这不是一个有效的解决方案。不过这个应该可以引出点子。
我基本上是在创建通讯录,我想在 JSON 上存储数据以进行练习。我已经从字典中排序了一个允许它的代码,但问题是当我重新 运行 脚本时,另一个字典被附加到现有的字典中,创建了几个额外的大括号,引发错误“End of预期文件。
这是代码:
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()
这是从中得出的 JSON 的样本:
{
"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"
}
}
前四个条目不会造成任何问题,因为它们附加在同一个 运行 中,但如果我退出程序并重新 运行 它(例如“g”),那么新字典造成冲突。有什么建议吗?
这样做的一种方法是,在添加到文件之前,删除最后一个右括号 }
并在转储之前,将字典转换为字符串并使用此 [=12 删除第一个括号=].
我为您编写的另一种方法是将 json 加载到变量中,添加新输入,然后将其重新转储到文件中
import json
from os import path # it helps to check if file exists
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:
# if the file doesn't exist, write an empty json object into it
# which will make it easier later to load data from
if not path.exists('contact_book.json'):
with open('contact_book.json', 'w+') as file:
json.dump({}, file)
# This loads the data into the variable dict called loaded_data
with open('contact_book.json', 'r') as file:
loaded_data = json.load(file)
for k, v in new_contacts.items():
loaded_data[k] = v
# redumps your data into the json file
with open('contact_book.json', 'w') as file:
json.dump(loaded_data, file, indent=4)
break
contacts()
刚刚更新了您代码的其他部分。它检查 文件是否存在 。如果存在,则读取并更新文件的内容,然后将其转储到文件中。如果它不存在,您的旧代码将被执行。
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
老实说,这不是一个有效的解决方案。不过这个应该可以引出点子。