Python遍历json文件,并更换变量

def update_reuqest_body_file(self,request_body_filepath):
    read_json = ReadJson()
    content = read_json.read_json(request_body_filepath)
    # print(content)
    return self.replace_params_for_json(content)

#需要理解递归的思想

def replace_params_for_json(self, json_data):
    # 遍历json并替换变量
    for key, value in json_data.items():
        # print('%s %s' % (key, value))
        if type(value) == dict:
                #json类型的类型需要处理
            self.replace_params_for_json(value)
        elif type(value) == list:
        ​​​​​​​        #json list 需要特别处理
            for sub_value in value:
                self.replace_params_for_json(sub_value)
        else:
            if value is not None and type(value) == str and len(value) >= 1 and "${" in value and "}" in value:
                json_data[key] = self.update_variable(value)
    return json_data

前提是需要把值先存储到全局变量GLOBAL_VARIABLES中

def update_variable(self,data):
    print("data: "+data)
    if "${" in data and "}" in data:
        v = data[data.index("${") + 2:data.index("}")]
        return GLOBAL_VARIABLES.get(v)
    else:
        return data.strip()

其他的读取json方法

def read_all_json(self, json_string):
    # 遍历json 遍历字典
    dict_all = {}
    a = json.dumps(json_string, sort_keys=True)
    b = json.loads(a)
    c = b.items()
    for key, v in c:
        dict_all[key] = v
        print('%s %s' % (key, v))
        if type(v) == dict:
            self.read_all_json(v)
    return dict_all

你可能感兴趣的:(Python,json,restful,后端)