【Python】递归获取嵌套json 的所有key及value值
代码
class recurPostDict: """ 递归获取多维嵌套字典所有层级的key和value """ def __init__(self, datas): self.datas = datas def recur_data(self, data: dict, result=""): """多维/嵌套字典数据无限遍历,获取所有key层和value""" # 使用isinstance检测数据类型:字典类型 if isinstance(data, dict): for k, v in data.items(): if result == "": self.recur_data(v, k) else: self.recur_data(v, result+"_%s" % str(k)) # 列表或元组类型 elif isinstance(data, (list, tuple)): if len(data) == 1: for i in range(len(data)): # 自我调用实现无限遍历,单个不加修饰 self.recur_data(data[i], result) else: for i in range(len(data)): # 自我调用实现无限遍历,多个增加字母修饰 self.recur_data(data[i], result+"_%s" % public_tools.forward("a", i)) else: # print(result + "=" + str(data)) self.datas[result] = str(data)
运行:
if __name__ == "__main__": dic = {"name": "zhangsan", "address": {"sheng": "beijing", "shiji": "beijing", "shiqu": ["shijingshan", "p"], "qu": {"1dong": "1", "2dong": "2"}}} t = recurPostDict({}) # 传入空字典{},即datas初始值为{} t.recur_data(dic, result="") # 执行过程 print(t.datas) print(t.datas.keys()) print(t.datas.values())
执行结果
public_tools.forward() 字母表循环迭代实现地址:https://www.cnblogs.com/phoenixy/p/17126439.html
def params_to_line(content: str): col_name = [] col_value = [] for key, value in up_colname.items(): if type(value) == list: if len(value) == 0: pass elif len(value) == 1: for sub_key, sub_value in value[0].items(): sub_key = key + "_" + sub_key col_name.append(sub_key) col_value.append(sub_value) else: for i in range(len(value)): for sub_key, sub_value in value[i].items(): sub_key = key + "_" + sub_key + "_" + public_tools.forward("a", 5) col_name.append(sub_key) col_value.append(sub_value) else: logs.warning(f"解析参数时, 出现字符串、字典、列表以外的{type(value)}类型,无法将{key}对应的字段落库 ~")
-------------------------------------------------------------------------------------
如果万事开头难 那请结局一定圆满 @ Phoenixy
-------------------------------------------------------------------------------------