嘿,我有一个 json 文件,例如: [ { “记者”:“abc”, "创建": "2015-05-28 11:29:16", “受让人”:“ABC”, “ key ”:“JIRA-123” }, { “记者”:“def”, "创建": "2015-05-28 11:29:16", “受让人”:“DEF”, “ key ”:“JIRA-234” } ]
按照上述格式,现在我需要从动态生成的数据中向该文件添加更多条目,让我们说下面的数据
{
"Reporter": "xyz",
"Created": "2015-05-28 11:29:16",
"Assignee": "XYZ",
"Key": "JIRA-456"
},
{
"Reporter": "utf",
"Created": "2015-05-28 11:29:16",
"Assignee": "UTF",
"Key": "JIRA-678"
}
但是当我将此数据更新到上面的 json 文件中时,它再次将有一个单独的列表而不是组合。
喜欢:
[
{
"Reporter": "abc",
"Created": "2015-05-28 11:29:16",
"Assignee": "ABC",
"Key": "JIRA-123"
},
{
"Reporter": "def",
"Created": "2015-05-28 11:29:16",
"Assignee": "DEF",
"Key": "JIRA-234"
}
]
[
{
"Reporter": "xyz",
"Created": "2015-05-28 11:29:16",
"Assignee": "XYZ",
"Key": "JIRA-456"
},
{
"Reporter": "utf",
"Created": "2015-05-28 11:29:16",
"Assignee": "UTF",
"Key": "JIRA-678"
}
]
但我想要的是以下格式
[
{
"Reporter": "abc",
"Created": "2015-05-28 11:29:16",
"Assignee": "ABC",
"Key": "JIRA-123"
},
{
"Reporter": "def",
"Created": "2015-05-28 11:29:16",
"Assignee": "DEF",
"Key": "JIRA-234"
},
{
"Reporter": "xyz",
"Created": "2015-05-28 11:29:16",
"Assignee": "XYZ",
"Key": "JIRA-456"
},
{
"Reporter": "utf",
"Created": "2015-05-28 11:29:16",
"Assignee": "UTF",
"Key": "JIRA-678"
}
]
我尝试了 r+ 和 a+ 模式,但没有得到我想要的。
with open(os.path.abspath(os.path.join(os.path.dirname(__file__), 'static', 'result', file_name + '_issues.json')), 'r+') as nInfo:
nInfo.write(json.dumps(file_data,indent=4, separators=(',', ': ')))
任何人都可以帮助实现这一目标吗?
发送! VK
最佳答案
假设您的 json 文件包含对象列表:
首先从文件加载 json
with open('file.json') as f:
oldjson = json.load(f)
然后用新的字典更新 json 并覆盖文件
oldjson.append(list_of_dicts)
with open('file.json', 'w') as f:
f.write(json.dumps(oldjson, indent=4, separators=(',', ': ')))
关于python - 如何使用 json 数据更新现有的 json 文件 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30515424/