Search code examples
pythonjsonfunctionargs

Python function to get a JSON value based on optional number of arguments


How can I create python function which is able to get specific value from json based on provided arguments? The number of provided arguments should be optional as I cannot know in advance how deep into the json structer I will need to go for the value.

    def json_get_value(respond, *args):
        
        
        try:
            my_json = json.loads(respond)

        except:
            print("Unable to load JSON")
            return "Error ..."

        try:
            value = my_json[args[0]][args[1]][args[2]]
            return value
        except KeyError: 
            return "None"

answer = json_get_value(respond, "count_categories", 0, "total", ........)        

My question is how I can change this line: value = my_json[args[0]][args[1]][args[2]....] so the function will be universal for any number of arguments and so for any number of keys to get the desired value. I know that in case with *args is often used a for cycle, but in this case I am not sure how to utilize for cycle for this purpose.

Thanks a lot for any help.


Solution

  • A possible solution is to use your variable value to keep the current level in the JSON tree in which you are:

    try:
        value = my_json
        for arg in args:
            value = value[arg]
        return value
    except KeyError: 
        return "None"
    

    Note that, if no args are passed, this function simply returns the parsed json file.