首页 > 解决方案 > 使用 jq 获取选定对象的父键

问题描述

我在这里问了一个关于从 JSON 结构中获取键和值的问题:Using jq to get key and value from JSON

这是 JSON:

{
 "63": {
    "state": {
      "on": false,
      "alert": "select",
      "mode": "automation",
      "reachable": true
    },
    "swupdate": {
      "state": "notupdatable",
      "lastinstall": "2019-09-15T11:19:15"
    },
    "type": "plug",
    "name": "Tree",
    "modelid": "XXX",
    "manufacturername": "XXX",
    "productname": "plug",
    "capabilities": {
      "certified": false,
      "control": {},
      "streaming": {
        "renderer": false,
        "proxy": false
      }
    },
    "config": {
      "archetype": "plug",
      "function": "functional",
      "direction": "omnidirectional"
    },
    "uniqueid": "00:0d:6f:ff:fe:da:c9:dc-01",
    "swversion": "2.0.022"
  }
}

我只想根据 .name 的内容发出对象的父键:其中 .name == "Tree",返回 "63"。

我可以发出整个对象:

jq -r '.[] | select(.name == "Tree")'

或键和名称列表:

jq -r 'map_values(.name)'

标签: jsonjq

解决方案


您可以使用键/值格式格式化 JSONto_entries()并获取与某个值对应的键

jq --raw-output 'to_entries[] | select(.value.name == "Tree").key'

推荐阅读