需要从包含特定字符“/”的 JSON 中获取所有键值对

2024-06-22

我有一个特定的 json 内容,我需要获取其值中包含字符 / 的所有键。

JSON

{ "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 'paths(type == "string" and 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: .}

Output:

{
  "binding": {
    "wf.example.input1": "/path/to/file1",
    "wf.example.input3": [
      "/path/to/file3",
      "/path/to/file4"
    ]
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

需要从包含特定字符“/”的 JSON 中获取所有键值对 的相关文章

随机推荐