Skip to content
Advertisement

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 on changing frquently so the keys position within the dictionary is not same everytime, i need to search for a key and print it corresponding value, Since the json string changes everytime I have written an recursive function(See below) to search for key in the new json string and print the value. However now the situation is we have same key multiple times with diff values, how can i get the complete path of the key so it would be easier to understand which 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 so far:

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)

Advertisement

Answer

You could add a string parameter that keeps track of the current JSON path. Something like the following could 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)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement