python - 如何使用 json 数据更新现有的 json 文件 python

标签 python json

嘿,我有一个 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/

相关文章:

python - 使用 Python 对元组中每个给定的第一个值求和元组中的第二个值

python - Kivy:获取小部件 ID 并通过唯一属性访问小部件

javascript - 使用 Ajax 从维基百科返回数据?

javascript - 如何使用 ajaxFileUpload jQuery 插件传递数据

ruby-on-rails - JSON 字符串到对象 - Ruby on Rails

javascript - 使用 JSON 对象数据填充 html 表

python - 通过 python/psycopg2 将 XML 转换为 Postgres

python - 如何避免立方和绝对值对数的数值溢出?

c# - 使用NEST搜索时出现JsonSerializationException

python - 使用 Scapy 更改数据包 - 在编辑数据包的有效负载后自动更新属性(长度、校验和等)