[英]Append Dictionary to JSON file
我正在嘗試 append 一個字典到一個 json 文件已經有 2 個字典。 但它在同一個 json 文件中給了我初始文件和結果。 我的代碼如下。 提前感謝人們。
import json
import os
cwd = os.getcwd()
fp = cwd + '/xero_credentials.json'
def json_append():
data_object = {
"clientName": "Company Test",
"clientId": "null",
"clientSecret": "null",
"redirect_url": "http://localhost:8080/callback",
'scopes': "offline_access accounting.transactions.read accounting.journals.read",
'refreshToken': "null"
}
with open(fp, 'r+') as json_file:
data = json.load(json_file)
data_dictionary = data['credentials']
data_dictionary.append(data_object)
json.dump(data, json_file, indent = 4, sort_keys=True)
json_file.close()
# **********
json_append()
這是結果:
{
"credentials": [
{
"clientName": "C1",
"clientId": "null"
},
{
"clientName": "C2",
"clientId": "null"
}
]
}
{
"credentials": [
{
"clientName": "C1",
"clientId": "null"
},
{
"clientName": "C2",
"clientId": "null"
},
{
"clientName": "C3",
"clientId": "null"
}
]
}
就地更新文件很困難(某些特殊情況除外),因此通常必須首先將其全部內容讀入 memory,更新,然后用它來重寫整個文件。
這就是我的意思:
import json
import os
cwd = os.getcwd()
fp = cwd + '/xero_credentials.json'
def json_append():
data_object = {
"clientName": "Company Test",
"clientId": "null",
"clientSecret": "null",
"redirect_url": "http://localhost:8080/callback",
'scopes': "offline_access accounting.transactions.read accounting.journals.read",
'refreshToken': "null"
}
# Read the entire file.
with open(fp, 'r') as json_file:
data = json.load(json_file)
# Update the data read.
credentials = data['credentials']
credentials.append(data_object)
# Update the file by rewriting it.
with open(fp, 'w') as json_file:
json.dump(data, json_file, indent=4, sort_keys=True)
json_append()
更新后的文件:
{
"credentials": [
{
"clientId": "null",
"clientName": "C1"
},
{
"clientId": "null",
"clientName": "C2"
},
{
"clientId": "null",
"clientName": "Company Test",
"clientSecret": "null",
"redirect_url": "http://localhost:8080/callback",
"refreshToken": "null",
"scopes": "offline_access accounting.transactions.read accounting.journals.read"
}
]
}
編輯:誤解了這個問題。
問題在於您在打開文件時使用的是“r+”模式。 這意味着您將能夠閱讀和 append 但不能編輯,這就是您正在嘗試做的事情。
只需with open(fp, 'w')
使用。
此外,您不需要顯式關閉文件。 上下文管理器,例如with
在您離開 scope 后自動執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.