嘿,我有一个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
发布于 2015-06-02 15:01:38
我想出了办法。
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(' ')发布于 2015-05-28 19:42:00
假设您的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=(',', ': ')))https://stackoverflow.com/questions/30515424
复制相似问题