Quantcast
Viewing all articles
Browse latest Browse all 14011

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 tosearch for a key and print it corresponding value, Since the json string changes everytime I have written an recursive function(See below) to searchfor 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 cani 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 = Jasmineapp.Fruits.White Flower = groovyapp.Trees.label.White Flower = Bogan

My code so far:

import jsonwith 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)

Viewing all articles
Browse latest Browse all 14011

Trending Articles