【问题标题】:Need to get all key value pairs from a JSON containing a specific character '/'需要从包含特定字符 '/' 的 JSON 中获取所有键值对
【发布时间】:2017-12-14 23:44:50
【问题描述】:

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

【问题讨论】:

    标签: json jq


    【解决方案1】:

    如果给定的输入与示例非常相似,则以下 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"
        ]
      }
    }
    

    【讨论】:

    • 你能解释一下这个命令到底在做什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多