Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a JSON map containing shell variables named in a list

My shell-fu is at a below-beginner level. I have a file that contains some lines that happen to be the names of environment variables.

e.g.

ENV_VAR_A
ENV_VAR_B
...

What I want to do is use this file to generate a JSON string containing the names and current values of the named variables using jq like this:

jq -n --arg arg1 "$ENV_VAR_A" --arg arg2 "$ENV_VAR_B" '{ENV_VAR_A:$arg1,ENV_VAR_B:$arg2}'

# if ENV_VAR_A=one and ENV_VAR_B=two then the preceding command would output 
# {"ENV_VAR_A":"one","ENV_VAR_B":"two"}

I'm trying to create the jq command through a shell script and I have no idea what I'm doing :(

like image 494
Adam Avatar asked Jan 27 '26 01:01

Adam


1 Answers

Short and sweet (if you have jq 1.5 or higher):

 jq -Rn '[inputs | {(.): env[.]}] | add' tmp.txt
like image 58
peak Avatar answered Jan 29 '26 17:01

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!