Python replaces the content of a field in json

foreword

In the process of alchemy, it is inevitable to use json files to save the label values ​​of some target detection or semantic segmentation tasks, but sometimes the key value or value batch of a certain label is wrong, then a small tool script is needed to Modify the json value.

the code

json example
For example, like the above-mentioned json, I want to modify all the value crosses of the labels in thousands of json to keyboard in batches, then I can read in the json, then convert it into str, and then replace it with the regularity of str, Finally, convert str to json. code show as below:

def change_json_tmp():

    json_p = "image_third_batch"
    out_p = "out"
    for fi in os.listdir(json_p):
        if fi.endswith('.json'):
            with open(os.path.join(json_p, fi), 'r', encoding='utf-8') as f:
                s = f.read()

            s = s.replace("cross", "keyboard") ##字符串正则转换
            json_out = json.loads(s)
            with open(os.path.join(out_p, fi), 'w', encoding='utf-8') as f:
                json.dump(json_out, f) 

Guess you like

Origin blog.csdn.net/weixin_42280271/article/details/128223201