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字符串中的键并打印值。然而,现在的情况是,我们有相同的键多次出现,但值不同,我该如何获取键的完整路径,以便更容易理解它是哪个键的值?例如,结果应该像这样:
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)
all_paths
将拥有所有被打印出来的数据。 - Blair