简体   繁体   English

jq 在多映射结构 JSON 中查找键名

[英]jq find a key name in multi-map structured JSON

I have this JSON object that maps the compatibility of patch sets to specific software versions.我有这个 JSON object,它将补丁集的兼容性映射到特定的软件版本。

{
   "compatibility":{
      "v7.11.x":[
         "7.12.1",
         "7.12.0",
         "7.11.2",
         "7.11.1",
         "7.11.0"
      ],
      "v7.13.x":[
         "7.14.2",
         "7.14.1",
         "7.14.0",
         "7.13.1",
         "7.13.0"
      ],
      "v7.15.x":[
         "8.1.0",
         "8.0.1",
         "8.0.0",
         "7.17.1",
         "7.17.0",
         "7.16.1",
         "7.16.0",
         "7.15.1",
         "7.15.0"
      ]
   }
}

Would it be possible for jq to return the patch set name (eg "v7.15.x") when given the specific version (eg "8.1.0")?给定特定版本(例如“8.1.0”)时, jq是否可以返回补丁集名称(例如“v7.15.x”)?

Yes, it's pretty straightforward actually.是的,实际上这很简单。

.compatibility | to_entries[] | select(.value | index("8.1.0")) .key

Online demo在线演示

In case it's unclear, the version string doesn't have to be hardcoded;如果不清楚,版本字符串不必硬编码; it may come from outside the program too:它也可能来自程序之外:

jq --arg version 8.1.0 '.compatibility | to_entries[] | select(.value | index($version)) .key'

If you need to query the same data set several times, it might be worth creating an index object, store it in a variable, and perform the lookup from there:如果您需要多次查询相同的数据集,可能值得创建索引 object,将其存储在变量中,然后从那里执行查找:

(.compatibility | with_entries({value: .key, key: .value[]})) as $lookup

# various ways to lookup multiple versions
| $lookup["8.0.1", "7.11.2"], $lookup["7.16.1"]
"v7.15.x"
"v7.11.x"
"v7.15.x"

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM