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

时间:2015-05-28 19:23:51

标签: python json

嘿,我有一个json文件,例如:     [     {         “记者”:“abc”,         “创造”:“2015-05-28 11:29:16”,         “受让人”:“ABC”,         “关键”:“JIRA-123”     },     {         “记者”:“def”,         “创造”:“2015-05-28 11:29:16”,         “受让人”:“DEF”,         “关键”:“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=(',', ': ')))

任何人都可以帮助实现这一目标。

TXS! VK

2 个答案:

答案 0 :(得分:1)

假设您的json文件包含对象列表:

首先从文件中加载你的json

with open('file.json') as f:
    oldjson = json.load(f)

然后使用新的dict更新json并覆盖文件

oldjson.append(list_of_dicts)
with open('file.json', 'w') as f:
    f.write(json.dumps(oldjson, indent=4, separators=(',', ': ')))

答案 1 :(得分:0)

我想出了办法。

with open(os.path.abspath(os.path.join(os.path.dirname(__file__),'static', 'result', file_name + '_issues.json')), 'r+') as nInfo:
  count = 0
  for data in file_data:
      count += 1
      if count == 1:
        nInfo.seek(-2, 2)
      if file_data.index(data) != len(file_data):
        nInfo.write(',')
      nInfo.write(json.dumps(data, default=lambda a: '[%s,%s]'(str(type(a)), a.pk)))
  nInfo.write(']')
  nInfo.write(' ')