python 遍历json文档并显示路径

背景:手头上有份json数据要把它解析成二维表的形式

import json

def dict_generator(indict, pre=None):
    pre = pre[:] if pre else []
    if isinstance(indict, dict):
        for key, value in indict.items():
            if isinstance(value, dict) :
                if len(value) == 0: #如果值为空
                    yield pre+[key, '{}'] #jsonPath加上空字典
                else: #如果值不为空则需要继续迭代
                    for d in dict_generator(value, pre + [key]):
                        yield d
            elif isinstance(value, list) and key != "附录(通话号码列列表)数据节点": #这个太长先不要
                if len(value) == 0:                   
                    yield pre+[key, '[]']
                else:
                    for v in value: #把列表中的元素拿出来迭代
                        for d in dict_generator(v, pre + [key]):
                            yield d
            elif isinstance(value, tuple):
                if len(value) == 0:
                    yield pre+[key, '()']
                else:
                    for v in value:
                        for d in dict_generator(v, pre + [key]):
                            yield d
            else: #如果不是'值'不是元组,列表,字典则输出结果
                yield pre + [key, value]
#     elif isinstance(indict, list):
    else:
        yield pre + [indict]

if __name__ == "__main__":
    sJSON = '{"a":1}' #可以弄复杂的json对象
    sValue = json.loads(sJSON)
    for i in dict_generator(sValue):
        print('.'.join(i[0:-1]), ':', i[-1])

你可能感兴趣的:(python数据分析)