0

I'm trying to extract value from the bellow JSON:

% export test='{"a-b-c":"x-y-z"}'
% echo $test
{"a-b-c":"x-y-z"}
% echo $test | jq .a-b-c
jq: error: b/0 is not defined at <top-level>, line 1:
.a-b-c
jq: error: c/0 is not defined at <top-level>, line 1:
.a-b-c
jq: 2 compile errors
% echo $test | jq '."a-b-c"'
"x-y-z"
%

while the last line "works", my end goal is to have shell script and substitute "a-b-c" parameter with variable, however due to I must use single quotes, the actual value isn't being passed..

% export var1=a-b-c
% echo $var1
a-b-c
% echo $test | jq '."$var1"'
null
%

Please advise)

alexus
  • 13,112
  • 32
  • 117
  • 174

2 Answers2

2

Use the --arg option to initialize a jq variable with a shell variable's value.

jq --arg key "$var1" '.[$key]'

See Invoking jq and scroll down to --arg

glenn jackman
  • 4,630
  • 1
  • 17
  • 20
0

I've got it to work:

% echo $test | jq ".\"$var1\""
"x-y-z"
%

Thanks!

alexus
  • 13,112
  • 32
  • 117
  • 174