You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jq通过OS版本查找未知的父级OS节点内容?

使用jq通过OS版本获取对应父级OS节点内容

需求

已知具体OS版本(如18.04),获取该版本所属的父级OS节点的全部内容(如ubuntu节点的完整数据),且预先不知道父节点的键名。例如搜索7.4时,需返回整个rhel节点内容。

示例JSON结构

{"os": {"ubuntu": {"16.04": {"codename": "xenial","bootstrap": "preseed","guest_type": "ubuntu64Guest","iso_name": "ubuntu-16.04.7-server-amd64.iso","iso_checksum": "9bb30a2ea6466b0c02aacfa96f6e3516"},"18.04": {"codename": "bionic","bootstrap": "preseed","guest_type": "ubuntu64Guest","iso_name": "ubuntu-18.04.2-server-amd64.iso","iso_checksum": "34416ff83179728d54583bf3f18d42d2","arm": {"iso_name": "ubuntu-18.04.5-server-arm64.iso","iso_checksum": "5056eaf87425b550376e6733b05de6e9"}}},"rhel": {"7.4": {"codename": "maipo","bootstrap": "kickstart","guest_type": "rhel7_64Guest","iso_name": "rhel-server-7.4-x86_64-boot.iso","iso_checksum": "94ad0929b79b5d13b33acafc8da8d364"},"7.6": {"codename": "maipo","bootstrap": "kickstart","guest_type": "rhel7_64Guest","iso_name": "rhel-server-7.6-x86_64-boot.iso","iso_checksum": "4a611d2bbfa6912eada91096af14ec84"}}}}

解决方案

使用以下jq命令,通过传入版本号参数实现需求:

jq --arg target_version "18.04" '.os | to_entries[] | select(.value | has($target_version)) | .value' your_os_config.json

命令拆解

  • --arg target_version "18.04":将目标版本号作为参数传入,便于快速替换不同版本(比如改成"7.4"即可搜索RHEL节点)
  • .os:定位到JSON顶层的os节点
  • to_entries[]:将os下的键值对(如ubuntu: {...})转换为{"key": "ubuntu", "value": {...}}的结构化格式,方便遍历筛选
  • select(.value | has($target_version)):筛选出value中包含目标版本号作为键的条目
  • .value:输出筛选出的条目对应的父级OS节点完整内容

扩展:同时输出父节点键名

如果需要同时返回父节点的名称(如ubuntu/rhel),可以修改命令为:

jq --arg target_version "18.04" '.os | to_entries[] | select(.value | has($target_version)) | {os_name: .key, details: .value}' your_os_config.json

内容的提问来源于stack exchange,提问作者Guillaume

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 13:55:17