Home > Net >  Create JSON of environment variables name-value pairs from array of environment variable names with
Create JSON of environment variables name-value pairs from array of environment variable names with

Time:11-24

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

CodePudding user response:

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.

CodePudding user response:

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

  • Related