I want to parse a JSON file and get the full a list containing all the required paths to access keys. If we use the keys method we get a list of individual keys but not the full list of hierarchical keys needed to access the data.
So if given data as such
data = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
I could return a list like below containing all the full paths to the keys.
[['glossary']['title'],['glossary']['GlossDiv']...]
Reading and accessing elements is fine. to acheive the result I have tried to use this SO answer Access nested dictionary items via a list of keys
I don't really understand how this works and it returns only the word 'glossary'.
This is my code. I was using ChainMap as it made it easier to convert json to a dictionary and easily access keys.
import json
from collections import ChainMap
from functools import reduce
import operator
myDataChained = ChainMap(data)
def getFromDict(data):
return reduce(operator.getitem, data)
Json_Paths = getFromDict(myDataChained)
print(Json_Paths)