是否可以从json文件中替换dict中的多个键。 我将尝试用简单的示例来解释我的问题: 我有一个像这样的json文件:
"a1": {
"option": "2",
"suboption": "2",
"option": "2",
"suboption_device": "3",
"option": "1",
"suboption_ip": "1",
"option": "1",
"suboption_ip": "2"
}
我的拳头测试看起来像这样:
def replace_option(match):
global o
o += 1
return 'option%o' % o
def replace_suboption(match):
global s
s += 1
return 'suboption%s' % s
def preProcessing():
with open('test.json') as f:
data = f.read()
replace1 = json.loads(re.sub("option", replace_option, data))
replace2 = json.loads(re.sub("suboption", replace_suboption, data))
所以在replace1
消失了所有suboption_ip
和replace2
所有option
除了一个。
感谢您帮助我:)
编辑:
replace1
的输出:
"a1": {
"option1": "2",
"suboption": "2",
"option2": "2",
"suboption_device": "3",
"option3": "1",
"suboption_ip": "1",
"option4": "1",
}
replace2
的输出:
"a1": {
"option": "2",
"suboption1": "2",
"suboption2_device": "3",
"suboption3_ip": "1",
"suboption4_ip": "2"
}
答案 0 :(得分:0)
简单易用:
with open(INFILE, "rt") as f:
with open(OUTFILE_BLOCK, "wt") as o:
for line in f:
i += 1
o.write(line.replace("pn_dcp.block", "pn_dcp.block%i" %i))
i = 0
with open(OUTFILE_BLOCK, "rt") as f:
with open(OUTFILE_OPTION, "wt") as o:
for line in f:
i += 1
o.write(line.replace("pn_dcp.option", "pn_dcp.option%i" %i))
i = 0
with open(OUTFILE_OPTION, "rt") as f:
with open(OUTFILE_FINAL, "wt") as o:
for line in f:
i += 1
o.write(line.replace("pn_dcp.suboption", "pn_dcp.suboption%i" %i))
i = z