Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading