这让我发疯,感谢您的帮助。这是我想要做的:
使用JSON文件作为输入,找到两个连续的行,如下所示:
{
"description"
然后,如果找到该条件,请在此点上方插入其他JSON。遵循代码几乎的方法除了出于某种原因,我出于某种原因无法理解,因此跳过了一行。
代码:
with open('file.in',encoding="utf8") as in_file:
with open('file.out','w',encoding="utf8") as out_file:
tag_to_check_line1 = '{'
tag_to_check_line2 = '"description"'
tag_to_check_not_line2 = ',"description"'
irofile = iter(in_file)
for line in irofile:
if tag_to_check_line1 in line:
out_file.write(line)
line = next(irofile)
if tag_to_check_line2 in line and tag_to_check_not_line2 not in line:
out_file.write('\n')
out_file.write('"fields": {\n')
out_file.write('"project":\n')
out_file.write('{\n')
out_file.write('"key": "GID"\n')
out_file.write('},\n')
out_file.write(line)
else:
out_file.write(line)
输入数据如下:
{
"description": "<p>The description is here.</p>",
"customfield_16818": "REQ-7591",
"customfield_16819": "GID-1214020",
"customfield_16815":{"self":"https://jira.com/rest/api/2/customFieldOption/20685","value":"No","id":"20685"},
"summary": "MySQL Redundancy",
"customfield_16816": "0",
"customfield_16817": "0",
"tag": "tagtext"
}
除了缺少"summary"
标签之外,结果输出看起来正确:
{
"fields": {
"project":
{
"key": "GID"
},
"description": "<p>The description is here.</p>",
"customfield_16818": "REQ-7591",
"customfield_16819": "GID-1214020",
"customfield_16815":{"self":"https://jira.com/rest/api/2/customFieldOption/20685","value":"No","id":"20685"},
"customfield_16816": "0",
"customfield_16817": "0",
"tag": "tagtext"
}
所以问题是:为什么缺少"summary"
标签?
答案 0 :(得分:1)
您缺少else:
子句。可以如下所示进行固定:
with open('file.in',encoding="utf8") as in_file:
with open('file.out', 'w', encoding="utf8") as out_file:
tag_to_check_line1 = '{'
tag_to_check_line2 = '"description"'
tag_to_check_not_line2 = ',"description"'
irofile = iter(in_file)
for line in irofile:
if tag_to_check_line1 in line:
out_file.write(line)
line = next(irofile)
if tag_to_check_line2 in line and tag_to_check_not_line2 not in line:
out_file.write('\n')
out_file.write('"fields": {\n')
out_file.write('"project":\n')
out_file.write('{\n')
out_file.write('"key": "GID"\n')
out_file.write('},\n')
out_file.write(line)
else: # ADD THESE
out_file.write(line) # TWO LINES
else:
out_file.write(line)