简体   繁体   中英

How can I use a string representing a path of dict key as a dict key in Python?

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]]) .

# 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM