我想做的是在json上"walk",并为每个名为"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
]
}
}
}
}
}
非常感谢您的建议和专业知识!
这里有一种方法:
reduce paths(objects | has("base")) as $p (.;
setpath($p + ["path"]; $p | join("."))
)
在线演示
您可以使用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(".")))
)