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

Time:12-10

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.

CodePudding user response:

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.

CodePudding user response:

you could use a recursive function for this. So if you still have args then keep drilling into the json. If you have a key in your args list thats not in the JSON then return a None object, otherwise keep drilling down until you get the data

jdata = {
    "foo": 1,
    "bar": 2,
    "nest1": {
        "baz": "bar"
    },
    "nest2": {
        "nest3": {
            "nest4": {
                "hello": "world"
            }
        }
    }
}

def get_from_json(jdata: dict, *keys):
    try:
        data = jdata[keys[0]]
    except KeyError:
        return None
    if len(keys) > 1:
        return get_from_json(data, *keys[1:])
    return data

print(get_from_json(jdata, "nest2", "nest3", "nest4", "hello"))
print(get_from_json(jdata, "nest1"))
print(get_from_json(jdata, "nest2", "nest3"))
print(get_from_json(jdata, "val", "boo"))
print(get_from_json(jdata, "nest2", "nest3", "someval"))

OUTPUT

world
{'baz': 'bar'}
{'nest4': {'hello': 'world'}}
None
None
  • Related