英文:
Updating a dictionary in a JSON File
问题
试图更新JSON文件中的特定字典,但无法这样做,因为它只是将一个新字典添加到数据库而不是在字典下面。我尝试过将数据库转换为列表,然后将其追加到列表中,然后将其放入数据库,也尝试过使用update()函数,但两种方式都没有将其添加到字典下面。
英文:
Trying to update a certain dictionary in a json file but unable to do so as it just adds a new dictionary to the database rather than being under the dictionary.
An example, of what I'm trying to achieve is:
Before running the function the database looks like:
{
"account_details": [
{
"Username": "TestingUsername",
"Password": "232Pass",
"Email": "TestingEmail@outlook.com",
"Token": "18973871HIA"
}
]
}
After running the function this is what the database looks like:
{
"account_details": [
{
"Username": "TestingUsername",
"Password": "232Pass",
"Email": "TestingEmail@outlook.com",
"Token": "18973871HIA"
}
]
}{
"Username": "TestingUsername",
"Password": "232Pass",
"Email": "TestingEmail@outlook.com",
"Token": "18973871HIA",
"Details": {
"Preset1": {
"Username": "TestingUsername",
"Password": "TestingPassword3",
"URL": "TestingURL.com:"
}
}
}
The functions, function is to take in the Presetname (TestingPreset39), under the Details dictionary, which then includes the Username (Testing_username) , Password (TestingPresetPassword) & Url (preset.com).
However, what I want it to look like is:
{
"account_details": [
{
"Username": "ComputingCourse32",
"Password": "NoNUmbers",
"Email": "computingcw@cwl.com",
"Token": "4L8PWWRFYL",
"Testing": "Testing",
"Details": {
"Preset1": {
"Username": "Username1",
"Password": "Password1",
"URL": "http://testing.cwl.com"
}
}
},
I've tried to convert the database into a list as a way to append to the list then putting it in the database:
with open("testaccount.json", "r+") as file:
data = json.load(file)
for record in data["account_details"]:
if record["Username"] == username:
if type(record) is dict:
data = [record]
# data['specific_dict'].append(new_dict)
data.append ({
"Details" : {
"Preset1":{
"Username": "TestingUsername",
"Password": "TestingPassword",
"URL": "TestingURL.com"
}
}
})
print(data)
Also, I've tried to use the update() function:
with open("testaccount.json", "r+") as file:
data = json.load(file)
for record in data["account_details"]:
if record["Username"] == "TestingUsername":
new_data = {"Details":{
"Preset1":{
"Username": "TestingUsername",
"Password": "TestingPassword3",
"URL": "TestingURL.com:"
}
}}
record.update(new_data)
print(record)
Though both ways put the new data in the database neither ways actually add it under the dictionary.
答案1
得分: 1
使用文件中的
json
格式数据,您不能可靠地覆盖文件的部分。您应该读取整个文件,将更改作为Python对象进行,最后将整个文件重新写入。 – quamrana
您可以使用以下代码来实现这一点。
with open('testaccount.json', 'r') as f:
data = json.load(f)
for ri, record in enumerate(data["account_details"]):
if record["Username"] == "TestingUsername":
new_data = {'Details': {'Preset1': {
'Username': 'TestingUsername',
'Password': 'TestingPassword3',
'URL': 'TestingURL.com:' }}}
data["account_details"][ri].update(new_data)
with open('testaccount.json', 'w') as f:
json.dump(data, f, indent=4)
请注意,*record.update(new_data)
*不会影响data
,因为record
只是data["account_details"][ri]
的副本。
英文:
> With json
format data in a file, you cannot reliably overwrite parts of the file. You should read the entire file, make changes as python objects, and finally write the entire file back. – quamrana
You can do so with the code below.<sup>(view result)</sup>
with open('testaccount.json', 'r') as f:
data = json.load(f)
for ri, record in enumerate(data["account_details"]):
if record["Username"] == "TestingUsername":
new_data = {'Details': {'Preset1': {
'Username': 'TestingUsername',
'Password': 'TestingPassword3',
'URL': 'TestingURL.com:' }}}
data["account_details"][ri].update(new_data)
# print(data)
with open('testaccount.json', 'w') as f:
json.dump(data, f, indent=4)
<sup>Note that record.update(new_data)
would not affect data
as record
is just a copy of data["account_details"][ri]
.</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论