Lorccan
Lorccan

Reputation: 823

Use jq to get parent key for a selected object

I asked a question about getting a key and value from a JSON structure here: Using jq to get key and value from JSON

This is the 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"
  }
}

I want to emit only the parent key for an object based on the contents of .name: where .name == "Tree", return "63".

I can emit the whole object with:

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

or a list of key and name with:

jq -r 'map_values(.name)'

Upvotes: 1

Views: 784

Answers (1)

Inian
Inian

Reputation: 85530

You can format the JSON in a key/value format using to_entries() and get the key corresponding to a certain value

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

Upvotes: 3

Related Questions