Home > Net >  How to do double-indirection with jq variables?
How to do double-indirection with jq variables?

Time:05-14

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
]

CodePudding user response:

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
]

CodePudding user response:

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"}'
  • Related