Python遍历json多层级key,输出json所有层级key和value值

发布于:2025-03-09 ⋅ 阅读:(17) ⋅ 点赞:(0)
import json

json_data = json.load(open(
    "data.json", "r", encoding="utf-8"))

def replace_params_for_json(json_data):

    result= {}

    def recursive_extract(d, prefix=""): #递归函数
        if isinstance(d, dict):
            for key, value in d.items():
                new_key = f"{prefix}.{key}" #创建新的键名
                recursive_extract(value, new_key) #调用递归
        elif isinstance(d,list):  #如果的是列表
            for index, item in enumerate(d):
                new_key = f"{prefix}.[{index}]" #创建新的键名
                recursive_extract(item, new_key)#调用递归

        else: #如果是基本类型
            result[prefix] =d #将结果添加到字典中
    recursive_extract(json_data)  #          #调用递归
    return result

result =replace_params_for_json(json_data)
print(result)
for i in result:
    print(i)

最后输出所有层级key对应值value
for key, value in result.items():
    print(f"{key}:{value}")

python获取多层json的key和value_mob649e815c3b9e的技术博客_51CTO博客

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方法