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

min*_*bro 5 python json dictionary

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"
            }
        }
    }'
Run Code Online (Sandbox Code Playgroud)

这是我的 json 字符串,它经常变化,所以字典中的键位置每次都不相同,我需要搜索一个键并打印它对应的值,因为每次我编写递归函数时 json 字符串都会改变(参见下面)在新的 json 字符串中搜索 key 并打印值。但是现在的情况是我们多次拥有相同的密钥和不同的值,我如何获得密钥的完整路径,以便更容易理解它是哪个密钥值,例如结果应该是这样的:

app.Garden.Flowers.white Flower = Jasmine
app.Fruits.White Flower = groovy
app.Trees.label.White Flower = Bogan
Run Code Online (Sandbox Code Playgroud)

到目前为止我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

Bri*_*ien 2

您可以添加一个字符串参数来跟踪当前的 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)
Run Code Online (Sandbox Code Playgroud)

你可以这样称呼它:

all_paths = []
find(element_to_search,j,'',all_paths)
Run Code Online (Sandbox Code Playgroud)