3

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

2
  • 1
    Why don't you use env? Commented Nov 24, 2022 at 7:26
  • If not limited to jq, 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 Commented Nov 24, 2022 at 7:36

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.