0

I have strings that represent JSON key paths. I would like to use those to go get the actual value of that path inside of my nested JSON data, like so:

path_a = "['id']"
path_b = "['users'][0]['address']['street']"
path_c = "['houses'][2]['block'][0]['is_viable']"

print(json_data[path_a])
print(json_data[path_b])
print(json_data[path_c])

As you guessed, the print returns an error:

KeyError: "['id']"

Is there a way to achieve what I'm trying to do? I gave a few examples of paths here but the main thing about my code is that I cannot know in advance how many "keys" will be in a path, so I cannot simply type print(json_data[path[0]][path[1]][path[2]][path[3]][path[4]]).

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Pxmme
  • 1
  • 1
  • 1
    Yes, there's a way to achieve it. You need to parse the string to something more usable, then apply e.g. https://stackoverflow.com/q/14692690/3001761. – jonrsharpe Mar 28 '22 at 21:57
  • @Pxmme for example in 1st print you need to print the value with key id i e. json_data['id'] ? Is my understanding right? – Vaibhav Jadhav Mar 28 '22 at 22:10
  • Hey @jonrsharpe, thanks, this worked!! Thanks a lot. How can I "mark" this issue as "Resolved"? I'm new here, sorry :( – Pxmme Mar 29 '22 at 11:30

1 Answers1

0
# Get a given data from a dictionary with position provided as a list
def getFromDict(dataDict, mapList):    
    for k in mapList: dataDict = dataDict[k]
    return dataDict

# Set a given data in a dictionary with position provided as a list
def setInDict(dataDict, mapList, value): 
    for k in mapList[:-1]: dataDict = dataDict[k]
    dataDict[mapList[-1]] = value

Those functions worked like a charm with what I was trying to do!

Pxmme
  • 1
  • 1