Sayth Renshaw wrote: > >> myjson = ... >> path = "['foo']['bar'][42]" >> print(eval("myjson" + path)) >> >> ? >> >> Wouldn't it be better to keep 'data' as is and use a helper function like >> >> def get_value(myjson, path): >> for key_or_index in path: >> myjson = myjson[key_or_index] >> return myjson >> >> path = ['foo', 'bar', 42] >> print(get_value(myjson, path)) >> >> ? > > Currently I do leave the data I extract the keys out as a full path. > > If I use pprint as suggested I get close. > > ['glossary'], > ['glossary', 'title'], > ['glossary', 'GlossDiv'], > ['glossary', 'GlossDiv', 'title'], > ['glossary', 'GlossDiv', 'GlossList'], > ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry'], > ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'ID'], > ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'SortAs'], > ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossTerm'], > ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'Acronym'], > ...] > > But to select elements from the json I need the format > json['elem1']['elem2] . > > I want to be able to get any json in future and parse it into my function > and return a list of all json key elements. > > Then using this cool answer on SO > https://stackoverflow.com/a/14692747/461887 > > from functools import reduce # forward compatibility for Python 3 > import operator > > def getFromDict(dataDict, mapList): > return reduce(operator.getitem, mapList, dataDict)
Note that my -- not so cool ;) -- function >> def get_value(myjson, path): does the same in a way that I expected to be easier to understand than the functional idiom. > def setInDict(dataDict, mapList, value): > getFromDict(dataDict, mapList[:-1])[mapList[-1]] = value > > Then get the values from the keys >>>> getFromDict(dataDict, ["a", "r"]) > 1 > > > That would mean I could using my function if I get it write be able to > feed it any json, get all the full paths nicely printed and then feed it > back to the SO formula and get the values. OK, if this is really just about printing >>> path = ["foo", "bar", 42] >>> print("".join("[{!r}]".format(key) for key in path)) ['foo']['bar'][42] > > It would essentially self process itself and let me get a summary of all > keys and their data. > > Thanks > > Sayth -- https://mail.python.org/mailman/listinfo/python-list