JSON获取嵌套字典中的键路径

aelbi1ox  于 2023-06-25  发布在  其他
关注(0)|答案(4)|浏览(109)
json = '{
    "app": {
        "Garden": {
            "Flowers": {
                "Red flower": "Rose",
                "White Flower": "Jasmine",
                "Yellow Flower": "Marigold"
            }
        },
        "Fruits": {
            "Yellow fruit": "Mango",
            "Green fruit": "Guava",
            "White Flower": "groovy"
        },
        "Trees": {
            "label": {
                "Yellow fruit": "Pumpkin",
                "White Flower": "Bogan"
            }
        }
    }'

这是我的json字符串,它不断变化,所以字典中的键位置每次都不一样,我需要搜索一个键并打印它对应的值,因为json字符串每次都改变我写了一个递归函数(见下文)来搜索新的json字符串中的键并打印值。然而现在的情况是,我们有相同的key多次与diff值,我如何才能获得key的完整路径,以便更容易理解它是哪个key值,例如结果应该是这样的:

app.Garden.Flowers.white Flower = Jasmine
app.Fruits.White Flower = groovy
app.Trees.label.White Flower = Bogan

我的代码:

import json
with open('data.json') as data_file:    
  j = json.load(data_file)

def find(element, JSON):    
  if element in JSON:
    print JSON[element].encode('utf-8')
  for key in JSON:
    if isinstance(JSON[key], dict):
      find(element, JSON[key])
 

find(element to search,j)
yx2lnoni

yx2lnoni1#

您可以添加一个字符串参数来跟踪当前JSON路径。下面的方法可以起作用:

def find(element, JSON, path, all_paths):    
  if element in JSON:
    path = path + element + ' = ' + JSON[element].encode('utf-8')
    print path
    all_paths.append(path)
  for key in JSON:
    if isinstance(JSON[key], dict):
      find(element, JSON[key],path + key + '.',all_paths)

你可以这样称呼它:

all_paths = []
find(element_to_search,j,'',all_paths)
5ktev3wc

5ktev3wc2#

def getDictValueFromPath(listKeys, jsonData):
    """
    >>> mydict = {
        'a': {
            'b': {
                'c': '1'
            }
        }
    }
    >>> mykeys = ['a', 'b']
    >>> getDictValueFromPath(mykeys, mydict)
    {'c': '1'}
    """
    localData = jsonData.copy()
    for k in listKeys:
        try:
            localData = localData[k]
        except:
            return None
return localData

gist

wgxvkvu9

wgxvkvu93#

下面的代码片段将给予JSON中可访问的路径列表。它遵循JSON路径的约定,其中[]表示路径是一个列表。

def get_paths(source):
    paths = []
    if isinstance(source, collections.abc.MutableMapping):
        for k, v in source.items():
            if k not in paths:
                paths.append(k)
            for x in get_paths(v):
                if k + '.' + x not in paths:
                    paths.append(k + '.' + x)
    elif isinstance(source, collections.abc.Sequence) and not isinstance(source, str):
        for x in source:
            for y in get_paths(x):
                if '[].' + y not in paths:
                    paths.append('[].' + y)
    return paths
31moq8wy

31moq8wy4#

下面是Brian的答案的修改版本,它支持列表并返回结果:

def find(element, JSON, path='', all_paths=None):
    all_paths = [] if all_paths is None else all_paths
    if isinstance(JSON, dict):
        for key, value in JSON.items():
            find(element, value, '{}["{}"]'.format(path, key), all_paths)
    elif isinstance(JSON, list):
        for index, value in enumerate(JSON):
            find(element, value, '{}[{}]'.format(path, index), all_paths)
    else:
        if JSON == element:
            all_paths.append(path)
    return all_paths

用途:

find(JSON, element)

相关问题