JSON get key path in nested 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"
            }
        }
    }'

      

Here is my json string which keeps changing, so the position of the keys in the dictionary is not the same every time, I need to look up the key and print its corresponding value. As the json string changes every time I wrote a recursive function (see below) to search for a key in a new json string and print the value. However, now the situation is that we have the same key multiple times with diff values, how can I get the full path of the key, so it would be easier to understand what key value it is, for example, the result should be like this:

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

      

My code:

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

# j=json.loads(a)


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)

      

+3


source to share


2 answers


You can add a string parameter that tracks the current JSON path. The following might work:

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)

      



You would call it like this:

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

      

+2


source


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

0


source







All Articles