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 } }
jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like "\u03bc"). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.
If you want to strip the quotes, just pipe the output from this command to tr -d '"' . @hd1, that's only true if there aren't literal quotes. If someone's name is "Mack \"The Knife\" Smith" , you want it to change to Mack "The Knife" Smith , not Mack The Knife Smith .
jq is a lightweight and flexible command-line JSON processor. If you are a command line addict, you will like the official description. jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
So, to implement bash shell scripts using REST APIs, you must know how to parse the response of REST API (that is, parse JSON data). Jq is a program developed to filter JSON data. You can consider Jq like sed, awk, or grep program but designed specifically for filtering JSON data.
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 objectto_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 throughselect(.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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With