Python函数来获取基于可选参数数量的JSON值



如何创建能够根据提供的参数从json中获取特定值的python函数?提供的参数数量应该是可选的,因为我无法提前知道我需要在json结构体中深入到多深才能获得值。

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", ........)        

我的问题是如何更改这一行:value=my_json[args[0]][args[1]][args[2]….]因此,该函数对于任何数量的参数都是通用的,对于任何数目的键也一样,以获得所需的值。我知道在带有*args的情况下,经常使用for循环,但在这种情况下,我不确定如何使用for循环。

非常感谢你的帮助。

一个可能的解决方案是使用变量value来保持JSON树中的当前级别:

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

请注意,如果没有传递参数,此函数只返回解析后的json文件。

您可以使用递归函数来实现这一点。因此,如果您仍然有args,那么继续深入json。如果您的参数列表中有一个不在JSON中的键,那么返回一个None对象,否则继续向下搜索,直到获得数据

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"))

输出

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

最新更新