需要从包含特定字符"/"的JSON获取所有键值对 [英] Need to get all key value pairs from a JSON containing a specific character '/'

查看:139
本文介绍了需要从包含特定字符"/"的JSON获取所有键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a specific json content for which I need to get all keys which contains the character / in their values.

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("/"))'获取包含文件路径或文件路径数组的所有键.这会给我类似以下的输出:

I know I can get all the keys containing file path or array of file paths using query jq 'paths(type == "string" and contains("/"))'. This would give me an output like:

[ "binding", "wf.example.input1" ]
[ "binding", "wf.example.input3", 0]
[ "binding", "wf.example.input3", 1 ]

现在,我已将包含某些文件路径的所有元素作为它们的值,是否有办法获取相同的键和值,然后将其存储为另一个JSON?例如,在针对此问题提到的JSON中,我需要将输出作为另一个包含所有匹配路径的JSON进行获取.我的输出JSON应该如下所示.

Now that i have all the elements that contains some file paths as their values, is there a way to fetch both key and value for the same and then store them as another JSON? For example, in JSON mentioned for this question, I need to get the output as another JSON containing all the matched paths. My output JSON should look something like below.

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

推荐答案

如果给定的输入与示例非常相似,则以下jq过滤器将产生所需的输出,但是它不够鲁棒,并且在某些细节上有欠缺从问题描述中不清楚.但是,根据更精确的规范修改过滤器应该足够容易:

The following jq filter will produce the desired output if given input that is very similar to the example, but it is far from robust and glosses over some details that are unclear from the problem description. However, it should be easy enough to modify the filter in accordance with more precise specifications:

. 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获取所有键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆