python - 将字典附加到 JSON 文件
问题描述
我正在尝试将字典附加到已经有 2 个字典的 json 文件中。但它在同一个 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"
}
]
}
解决方案
就地更新文件很困难(除了一些特殊情况),因此通常必须首先将其全部内容读入内存,更新,然后用它来重写整个文件。
这就是我的意思:
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"
}
]
}
推荐阅读
- java - 如何使用 javaFX Canvas 绘制图像模式
- clojure - 如果找到字符串“john”,则读取包含数据的文件并将前后 10 个字符的值打印到新文件中
- android - 无需用户交互即可启用通知访问
- angular - 如何禁用 Highstocks 中的数据分组(npm:Angular-highcharts)
- r - 具有多个日期时间的非 equi 连接
- python - 删除熊猫数据框中具有特定值的行
- reactjs - 使用不变性助手`update`时如何使用我的索引作为键
- laravel - 使用 Laravel 刀片语法进行引导选项卡和路由
- r - GGplot2:绘制数据框中特定列的每年值
- sql-server - 如果一个表中的值从 Null 更改为另一个值,则触发