jq parsing get value [closed]

EDIT: After clarification in the comments, to retrieve the states of devices whose key begins with “dimmer”, use

jq '[ .devices | to_entries[] | select(.key | startswith("dimmer")) | .value = .value.state ] | from_entries' filename.json

Output:

{
  "dimmer1": "off",
  "dimmer2": "off"
}

This works as follows:

  • .devices selects the .devices attribute of the JSON object
  • to_entries explodes the object into an array of key-value pairs describing its attributes (the devices), which is to say that an attribute "foo": "bar" becomes an object { "key": "foo", "value": "bar" }, and the exploded object is expanded into an array of such objects (one for each attribute)
  • to_entries[] unpacks that array, in order to pipe it through
  • select(.key | startswith("dimmer")), which selects of the devices those whose key begins with dimmer
  • .value = .value.state restructures the key-value pair that describes the device so that the value is replaced with just its state attribute
  • [ all that ] makes a JSON array of all that, and
  • [ all that ] | from_entries converts the array of key-value pairs back to JSON objects.

Old answer (shortened), now obsolete but possibly of interest:

To retrieve the keys of the attributes of devices in an array:

jq '.devices | keys' filename.json

To retrieve the values (also in an array),

jq '[ .devices[] ]' filename.json

I wasn’t entirely sure which of those two you meant.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)