在python中获取json/dictionary中的所有键路径组合

2024-09-30 18:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够获得JSON文件中键的所有不同路径。我经常获得大的json,我不太确定各种数据元素可能在哪里。或者我需要查询数据的各种元素。可视化JSON的树是不争的。在

基本上,我想得到所有不同路径的列表,以使各种未来任务更容易。在

例如:

myjson = {'transportation':'car',
'address': {'driveway':'yes','home_address':{'state':'TX',
'city':'Houston'}},
 'work_address':{
'state':'TX',
'city':'Sugarland',
 'location':'office-tower',
 'salary':30000}}

如果我可以运行某种类型的循环,以下面的格式或以某种格式返回列表,那就太好了。。。。在

myjson['address']['driveway']

在myjson.address myjson.address.driveway myjson.address.home_地址 myjson.address.home_地址.城市 myjson.address.home_地址.状态 myjson.transportation myjson.work_地址 myjson.work_地址.城市 myjson.work_地址.位置 myjson.work_地址.工资 myjson.work_地址.状态

例如,我从

^{pr2}$

我想这有点管用,但我不知道如何使它无限迭代。例如,我如何将其构建为3-10层以上的深度?在


Tags: 数据路径json元素cityhome列表address
2条回答

很棒的片段!在

以下是管理列表的版本:

def get_keys(some_dictionary, parent=None):
    if isinstance(some_dictionary, str):
        return
    for key, value in some_dictionary.items():
        if '{}.{}'.format(parent, key) not in my_list:
            my_list.append('{}.{}'.format(parent, key))
        if isinstance(value, dict):
            get_keys(value, parent='{}.{}'.format(parent, key))
        if isinstance(value, list):
            for v in value:
                get_keys(v, parent='{}.{}'.format(parent, key))
        else:
            pass

我认为这应该符合你的要求:

myjson = {
    'transportation': 'car',
    'address': {
        'driveway': 'yes',
        'home_address': {
            'state': 'TX',
            'city': 'Houston'}
    },
    'work_address': {
        'state': 'TX',
        'city': 'Sugarland',
        'location': 'office-tower',
        'salary': 30000}
}


def get_keys(some_dictionary, parent=None):
    for key, value in some_dictionary.items():
        if '{}.{}'.format(parent, key) not in my_list:
            my_list.append('{}.{}'.format(parent, key))
        if isinstance(value, dict):
            get_keys(value, parent='{}.{}'.format(parent, key))
        else:
            pass


my_list = []
get_keys(myjson, parent='myjson')
print(my_list)

输出:

^{pr2}$

关键是在函数中继续递归地调用get_keys()!在

相关问题 更多 >