'How to do double-indirection with jq variables?

How to construct a name of a variable from data and access that variable?

For example it should somehow give the content of the alpha-file:

jq '$.var"-file"' --slurpfile alpha-file <(echo 0) --slurpfile beta-file <(echo 1) <<<'{"var": "alpha"}'

It should output:

[
  0
]


Solution 1:[1]

Named arguments are also available to the jq program as $ARGS.named.

So there is a dictionary to extract variables by a string name from:

jq '$ARGS.named["\(.var)-file"]' --slurpfile alpha-file <(echo 0) --slurpfile beta-file <(echo 1) <<<'{"var": "alpha"}'

outputs

[
  0
]

Solution 2:[2]

You could use getpath like this:

jq --slurpfile alphaFile <(echo 0) --slurpfile betaFile <(echo 1) '
   .var as $ab | {alpha: $alphaFile, beta: $betaFile} | getpath([$ab])' <<< '{"var": "alpha"}'

Better yet:

jq --slurpfile alpha <(echo 0) --slurpfile beta <(echo 1) '
   .var as $ab | {$alpha, $beta} | getpath([$ab])' <<< '{"var": "alpha"}'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Velkan
Solution 2