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

标签 json jq

我有一个特定的 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: .}

输出:

{
  "binding": {
    "wf.example.input1": "/path/to/file1",
    "wf.example.input3": [
      "/path/to/file3",
      "/path/to/file4"
    ]
  }
}

关于json - 需要从包含特定字符 '/' 的 JSON 中获取所有键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45025624/

相关文章:

javascript - 如何在 Nightmare.js 中处理 JSON 响应

php - 使用 PHP 从逗号分隔的字符串创建 JSON

python - 在 Flask 中发布 json 时出现“400 错误请求”

json - 使用 jq 将 x=y 对转换为键/值对

json - jq json对象连接到bash字符串数组

json - 将带有空格的 JSON 通过管道传输到 bash 数组中的最佳方法是什么?

json - 如何在 Spring MVC 中将字符串转换为对象

javascript - 'Uncaught TypeError: Cannot read property ' 的实例包含“null”

arrays - 使用 jq 删除与键匹配的对象和数组

json - 使用 jq 从每个主要节点版本获取最新版本