json - 从Python中的嵌套字典中获取键的绝对路径
问题描述
我在 python 中有一个字典对象,我会给一个方法提供两个参数,一个是一些键名键和一个 json 对象,我想接收一个具有键的绝对路径的输出。
示例 json 对象和键名是“年”
{
"name": "John",
"age": 30,
"cars": {
"car1": {
"name": "CD300",
"make": {
"company": "Benz",
"year": "2019"
}
}
}
}
我的功能将如下所示
def get_abs_path(json, key):
print(res)
预期输出 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')
推荐阅读
- r - 在 kable 列上添加渐变色标
- swift - iOS 14 奇数指针跳转,按位运算导致崩溃
- java - 打印出 for 循环中的数字
- python - 错误的BoundingBox尺寸提取pythonocc
- wagtail - 我将如何扩展 wagtailmenus LinkPage 以添加通用图片
- ruby - 在 irb 中定义一个名为 'method' 的方法时,出现了错误的参数数量
- android - react-native-vector-icons 中的错误,图标是日语
- python - 如何从 pandas sum / is in function 中获取一个数字
- javascript - 如何将普通文本和嵌入在同一条消息中?不和谐.js
- python - 提高将数据附加到文件的效率