[英]Use jq to get all parent keys of specific key
我想要做的是在我的 json 上“行走”,并为每个名为“base”的键添加一个键,该键是该键的完整“路径”。
这是我的 JSON:
{
"entity": {
"product": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": ["product", "products", "pdt", "pdts"]
}
},
"rabbit": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": ["rabbit", "rabbits"]
}
}
}
}
我想要这样的结果:
{
"entity": {
"product": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": ["product", "products", "pdt", "pdts"],
"path": "entity.product.title"
}
},
"rabbit": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": ["rabbit", "rabbits"]
"path": "entity.rabbit.title"
}
}
}
}
实际上,我实现了这一点,但我只得到一个子键:
walk(if type == "object" and .base then keys[] as $k | .base |= {path: $k} else . end)
结果:
{
"entity": {
"product": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": {
"path": "base"
}
}
},
"rabbit": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": {
"path": "base"
}
}
}
}
}
我也试过这个:
walk(if type == "object" and .base then paths(..) as $v | .base |= {path: $v} else . end)
结果:
{
"entity": {
"product": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": {
"path": [
"base",
3
]
}
}
},
"rabbit": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": {
"path": [
"base",
1
]
}
}
}
}
}
非常感谢您的建议和专业知识!
您可以使用path
获取路径的数组表示,使用join
连接它(假设简单,类似标识符的字段名称),并使用setpath
设置它:
jq '
reduce path((.. | objects | select(.base))) as $p (.;
setpath($p + ["path"]; $p | join("."))
)
'
{
"entity": {
"product": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": [
"product",
"products",
"pdt",
"pdts"
],
"path": "entity.product.title"
}
},
"rabbit": {
"att": {
"number_of_values": "Number of values"
},
"title": {
"base": [
"rabbit",
"rabbits"
],
"path": "entity.rabbit.title"
}
}
}
}
这是关于path
、 paths
、 setpath
和objects
的真正学习体验。 在阅读其他答案之前,我显然重新实现setpath
:
def add_path(p; val):
if p|length == 0
then .path = val
else .[p[0]] |= add_path(p[1:]; val)
end;
reduce ([paths(..) | select(last == "base")] | unique | map(.[:-1]))[] as $path (.;
add_path($path; ($path | join(".")))
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.