Ash*_*n S 2 json dictionary python-3.x
我在 python 中有一个字典对象,我将向一个方法提供两个参数,即某个键名 key 和 json 对象,我想接收一个包含该键的绝对路径的输出。
示例 json 对象,键名称为“year”
{
"name": "John",
"age": 30,
"cars": {
"car1": {
"name": "CD300",
"make": {
"company": "Benz",
"year": "2019"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的功能如下
def get_abs_path(json, key):
print(res)
Run Code Online (Sandbox Code Playgroud)
预期输出 res = cars.car1.make.company
def is_valid(json, key):
if not isinstance(json, dict):
return None
if key in json.keys():
return key
ans = None
for json_key in json.keys():
r = is_valid(json[json_key], key)
if r is None:
continue
else :
ans = "{}.{}".format(json_key, r)
return ans
a = {
"name": "John",
"age": 30,
"cars": {
"car1": {
"name": "CD300",
"make": {
"company": "Benz",
"year": "2019"
}
}
}
}
def get_abs_path(json, key):
path = is_valid(json, key)
print(path)
get_abs_path(a, 'company')
Run Code Online (Sandbox Code Playgroud)