问题描述
是否有可能从json文件中替换字典中的多个键。 我将尝试用简单的示例来解释我的问题:我有一个像这样的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
只有一个除外。
嗯...也许可以用一种方法执行替换过程? annybody有个主意吗?
感谢您的帮助:)
编辑:
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"
}
1楼
容易:
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