Expand environment variable from JSON file

jq provides access to its environment via a $ENV object - similar to perl's $ENV hash or awk's ENVIRON associative array. So for example assuming (as suggested by the accepted answer) your properties.json file looks like

{
  "environment": "USER"
}

then you can do

$ environment="$(jq -r '$ENV[.environment]' properties.json)"
$ echo "$environment"
steeldriver

(best to avoid ALLCAPS for your shell variables). If your file looks like

{
  "environment": "$USER"
}

including the shell-expansion $ then you can use the same method after removing the $:

environment="$(jq -r '$ENV[.environment | sub("^\\$";"")]' properties.json)"

Alternatively, you could pipe the result of a simple lookup through the external envsubst command:

$ environment="$(jq -r '.environment' properties.json | envsubst)"
$ echo "$environment"
steeldriver

See for example Replace environment variables in a file with their actual values?


Option 1: Just read variable by name

bash allows having variables that reference variables, example:

REF='USER'  # or get it from JSON
echo "${!REF}"
# prints current username

So you can write this:

ENVIRONMENT_REF="$(jq -r '.environment' "properties.json")"
ENVIRONMENT="${!ENVIRONMENT_REF}"

JSON contents:

"environment": "USER"

Option 2: Full shell expansion

Other option, maybe better (but definitely NOT secure) is using eval:

ENVIRONMENT="$(eval "echo $(jq -r '.environment' "properties.json")")"

Note that this is not secure and malicious code can be inserted to the JSON file. What malicious code? Let's look into this properties.json file:

{
    "environment": "$(rm some_file)" 
}

The shell will evaluate this code:

echo $(rm some_file)

… and the file named some_file will be deleted. As you can see, depending on the command entered there, you can cause very serious damage.