This is just a slight re-write of
one of the other answers.
In a Linux terminal, create a local folder:
$ mkdir -p ~/unix.se/jq/ && cd ~/unix.se/jq/
Create the file properties.json
:
$ echo '{"environment":"USER"}'>properties.json && cat properties.json
{"environment":"USER"}
A side note - pretty formatting with jq
:
$ jq '.' properties.json
{
"environment": "USER"
}
Use the value of the JSON key environment
, to
set a new environment variable and show its contents: 1
$ JQ_USER=$(jq -r '$ENV[.environment]' properties.json) && echo $JQ_USER
tedly
So far so good, but the problem is that I have been lying.(!) - The
properties.json
file does not look quite as above, as it has a dollar
sign in front of USER
, like so:
$ echo '{"environment":"$USER"}'>properties.json && cat properties.json
{"environment":"$USER"}
By getting rid of that disturbing dollar sign, for example by substituting the
empty string for it, we can get back to the already working solution:
$ JQ_USER=$(jq -r '$ENV[.environment | sub("\\$";"")]' properties.json)
echo $JQ_USER
tedly
1 When I first ran this, I got an error message starting with
jq: error: ENV/0 is not defined at <top-level>
.
It turns out that $ENV[]
requires version 1.6 (or later) of jq
.
$
symbol. Thanks for providing two options as well, and so quickly! – Stuart Leyland-Cole Feb 26 '21 at 17:52eval
is a security risk. It makes me feel better about upvoting :) Note that the system doesn't allow the asker to accept an answer in the first 15 minutes after posting, so Stuart cannot accept yet. – terdon Feb 26 '21 at 17:55