Json 需要从包含特定字符'/';
我有一个特定的json内容,我需要获取包含字符/的所有键 JSONJson 需要从包含特定字符'/';,json,jq,Json,Jq,我有一个特定的json内容,我需要获取包含字符/的所有键 JSON { "dig": "sha256:d2aae00e4bc6424d8a6ae7639d41cfff8c5aa56fc6f573e64552a62f35b6293e", "name": "example", "binding": { "wf.example.input1": "/path/to/file1", "wf.example.input2": "hello", "wf.example.input3
{ "dig": "sha256:d2aae00e4bc6424d8a6ae7639d41cfff8c5aa56fc6f573e64552a62f35b6293e",
"name": "example",
"binding": {
"wf.example.input1": "/path/to/file1",
"wf.example.input2": "hello",
"wf.example.input3":
["/path/to/file3",
"/path/to/file4"],
"wf.example.input4": 44
}
}
我知道我可以使用查询jq'路径(type==“string”和contains(“/”))
获取包含文件路径或文件路径数组的所有键。这将为我提供如下输出:
[ "binding", "wf.example.input1" ]
[ "binding", "wf.example.input3", 0]
[ "binding", "wf.example.input3", 1 ]
现在,我已经将包含一些文件路径的所有元素作为它们的值,有没有一种方法可以获取相同的键和值,然后将它们存储为另一个JSON?例如,在这个问题提到的JSON中,我需要将输出作为包含所有匹配路径的另一个JSON。我的输出JSON应该如下所示
{ "binding":
{ "wf.example.input1": "/path/to/file1",
"wf.example.input3": [ "/path/to/file3", "/path/to/file4" ]
}
}
如果给定的输入与示例非常相似,那么下面的jq过滤器将产生所需的输出,但它远远不够健壮,并且掩盖了问题描述中不清楚的一些细节。但是,根据更精确的规范修改过滤器应足够容易:
. as $in
| reduce paths(type == "string" and test("/")) as $path ({};
($in|getpath($path)) as $x
| if ($path[-1]|type) == "string"
then .[$path[-1]] = $x
else .[$path[-2]|tostring] += [$x]
end )
| {binding: .}
输出:
{
"binding": {
"wf.example.input1": "/path/to/file1",
"wf.example.input3": [
"/path/to/file3",
"/path/to/file4"
]
}
}
你能解释一下这个命令到底在做什么吗?