1

Requirement:

In a BASH script,

...iterate over an array of environment variable names as shown below:

arr = ('env_var1' 'env_var2' 'env_var3')

and, using jq generate a JSON of environment variable name-value pairs like below:

{
 "env_var1": "env_var1_value_is_1",
 "env_var2": "env_var2_value_is_2",
 "env_var3": "env_var3_value_is_3"
}

Current approach: Using this stackoverflow question's solution as a reference

printf '%s\n' "${arr[@]}" |
  xargs -L 1 -I {} jq -sR --arg key {} '{ ($key): . }' | jq -s 'add'

where arr array contains the environment variable names for which I want the values, however I am unable to interpolate the ${environment_variable_name} into the JSON's value in each key-value pair

  • 1
    Why don't you use [`env`](https://stedolan.github.io/jq/manual/#%24ENV%2Cenv)? – pmf Nov 24 '22 at 07:26
  • If not limited to `jq`, [jo](https://github.com/jpmens/jo) is a pretty cool tool, to construct JSON on the fly when the input is from an external source e.g. a bash array in this case – Inian Nov 24 '22 at 07:36

2 Answers2

2

How about

jq -n '$ARGS.positional | map({ (.): env[.] }) | add' --args "${arr[@]}"

Using $ARGS.positional with --args avoids the need to execute jq once per item in the array, and the env builtin is the thing you needed to pull values out of the environment.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • Thank you @hobbs! I believe you could guide me on the below as well. I input an object to my bash script which looks like `{"env_var1": "env_var_expected_val_1", "env_var2": "env_var_expected_val_2"}` and fetch all the keys (read: environment variable names) in an array i.e. `arr` with `jq -r 'keys[]'` which is inputed as the `${arr[@]}` to the above given command. Is there a way I could use the jq `pipe` to combine all into one command? – Somnath Pathak Nov 24 '22 at 09:35
1

Since by assumption the variables referenced in arr are environment variables, you could use printf along the lines of your attempt as follows:

printf '%s\n' "${arr[@]}" | jq -nR '[inputs | {(.): env[.] }] | add'

This also works with gojq and fq, and might be useful if your jq does not support $ARGS

peak
  • 105,803
  • 17
  • 152
  • 177