jq parsing get value

user3467696 picture user3467696 · Apr 1, 2015 · Viewed 47.8k times · Source

I need to get some values from a json file. I need to get a array (dimmer1, dimmer2)

Somebody any idea?

{
 "devices": {
    "dimmer1": {
      "protocol": ["kaku_dimmer"],
      "state": "off",
      "dimlevel": 1
    },
    "dimmer2": {
      "protocol": ["kaku_dimmer"],
      "state": "off",
      "dimlevel": 1
    }
}

Answer

Wintermute picture Wintermute · Apr 1, 2015

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.