JQ: access object by key variable

Viewed 80

Assume I have an object 'variables' containing a variable amount of unspecified other objects:

{
   "id":5,
   "variables":{
      "variable1":{
         "isSecret":null,
         "value":"value1"
      },
      "variable2":{
         "isSecret":null,
         "value":"value2"
      }
   }
}

What I need is a way to access both key name and the value of 'value' in the same loop.

I tried the following:

echo $service_connection | jq -r '.variables | keys[]' | while read variable; do
    echo $variable
    echo $service_connection | jq --arg var "$variable" -c '.variables[$var].value'
done

This gives me the following output:

variable1
null
variable2
null

To me, it seems like I would need something like

'.variables.$var'

or

'.variables.[$var]'

But jq can't parse it.

What am I doing wrong?

3 Answers

Using to_entries to split up the .variables object into an array of key-value pairs is also an option:

jq -r '.variables | to_entries[] | "\(.key): \(.value.value)"'
variable1: value1
variable2: value2

Demo

You don't need a bash intervention with a while read loop, do it all with jq

jq -r '.variables | keys_unsorted[] as $k | "\($k) \(.[$k].value)"'

produces a result as

variable1 value1
variable2 value2

jqplay - demo

jq '.variables | with_entries(.value |= .value)'
{
  "variable1": "value1",
  "variable2": "value2"
}
Related