json - jq parsing get value -
i need values json file. need array (dimmer1, dimmer2)
somebody idea?
{ "devices": { "dimmer1": { "protocol": ["kaku_dimmer"], "state": "off", "dimlevel": 1 }, "dimmer2": { "protocol": ["kaku_dimmer"], "state": "off", "dimlevel": 1 } }
edit: after clarification in comments, retrieve states of devices key begins "dimmer", use
jq '[ .devices | to_entries[] | select(.key | startswith("dimmer")) | .value = .value.state ] | from_entries' filename.json
output:
{ "dimmer1": "off", "dimmer2": "off" }
this works follows:
.devices
selects.devices
attribute of json objectto_entries
explodes object array of key-value pairs describing attributes (the devices), attribute"foo": "bar"
becomes object{ "key": "foo", "value": "bar" }
, , exploded object expanded array of such objects (one each attribute)to_entries[]
unpacks array, in order pipe throughselect(.key | startswith("dimmer"))
, selects of devices key beginsdimmer
.value = .value.state
restructures key-value pair describes device value replacedstate
attribute[ ]
makes json array of that, and[ ] | from_entries
converts array of key-value pairs json objects.
old answer (shortened), obsolete possibly of interest:
to retrieve keys of attributes of devices
in array:
jq '.devices | keys' filename.json
to retrieve values (also in array),
jq '[ .devices[] ]' filename.json
i wasn't entirely sure of 2 meant.
Comments
Post a Comment