【发布时间】:2015-08-11 11:37:50
【问题描述】:
嘿,我有一个 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=(',', ': ')))
任何人都可以帮助实现这一目标。
发送! VK
【问题讨论】:
-
我猜你应该从 JSON 加载数据,更新它并重写文件。我知道它虽然效率不高
-
我对python不太熟练,你的代码只显示了写作。所以我认为,您只需将新数据(序列化为文本)附加到文件中已经存在的文本后面。首先,我会将旧数据读入一个数组,将您的对象添加到该数组中,并用序列化数组的文本覆盖数据文件中的数据。如果您已经读入了数组,则将该代码放入问题中。