Jq parsing get value

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

Somebody knows?

{ "devices": { "dimmer1": { "protocol": ["kaku_dimmer"], "state": "off", "dimlevel": 1 }, "dimmer2": { "protocol": ["kaku_dimmer"], "state": "off", "dimlevel": 1 } } 
+6
source share
1 answer

EDIT: After clarification in the comments, to retrieve the states of devices whose key begins with a "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 a .devices object
  • to_entries blows up an object into an array of key-value pairs describing its attributes (devices), which means that the attribute "foo": "bar" becomes the object { "key": "foo", "value": "bar" } , and the exploded object expands into an array of such objects (one for each attribute)
  • to_entries[] unpacks this array to pass it through
  • select(.key | startswith("dimmer")) , which selects devices whose key begins with dimmer
  • .value = .value.state restructures a key-value pair describing the device, so that the value is replaced only by its state attribute
  • [ all that ] does a JSON array of all this and
  • [ all that ] | from_entries [ all that ] | from_entries converts an array of key-value pairs back to JSON objects.

The old answer (shortened), now obsolete, but perhaps interesting:

To get the device attribute keys in an array:

 jq '.devices | keys' filename.json 

To get the values ​​(also in the array),

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

I was not sure which of the two you had in mind.

+19
source

Source: https://habr.com/ru/post/984548/


All Articles