简体   繁体   中英

python replace more than one key from json data in dict

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:

   "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.

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 :

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

Output from replace2 :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM