python从dict中的json数据中替换多个键

时间:2022-07-24 07:37:02

is it possible to replace more than one key in a dict from a json file. I will try to explain my problem with simple expamples: I have a json File like this:

是否可以从json文件替换dict中的多个键。我将尝试用简单的示例来解释我的问题:我有一个像这样的json文件:

   "a1": {
      "option": "2",
      "suboption": "2",
      "option": "2",
      "suboption_device": "3",
      "option": "1",
      "suboption_ip": "1",
      "option": "1",
      "suboption_ip": "2"
    }

my fist test look like this:

我的拳头测试看起来像这样:

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))

so in replace1 disappear all suboption_ip and in replace2 all option except one.

因此在replace1中消除所有suboption_ip和replace2所有选项,除了一个。

hmm... Maybe it is possible to perform the replacement process in one method? Have annybody an idea?

嗯......也许有可能用一种方法进行更换过程吗?有个想法吗?

Thanks for helping me :)

谢谢你帮助我:)

EDIT:

Output from replace1:

replace1的输出:

"a1": {
  "option1": "2",
  "suboption": "2",
  "option2": "2",
  "suboption_device": "3",
  "option3": "1",
  "suboption_ip": "1",
  "option4": "1",
}

Output from replace2:

replace2的输出:

"a1": {
  "option": "2",
  "suboption1": "2",
  "suboption2_device": "3",
  "suboption3_ip": "1",
  "suboption4_ip": "2"
}

1 个解决方案

#1


0  

easy with:

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

#1


0  

easy with:

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