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 object
  • to_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 through
  • select(.key | startswith("dimmer")), selects of devices key begins dimmer
  • .value = .value.state restructures key-value pair describes device value replaced state 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

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -