Home > Net >  how to put 2 elements from jq variables in one request?
how to put 2 elements from jq variables in one request?

Time:02-01

There is a part of the script where each request receives a response and is written to a variable. How to do it in one request with writing to variables?

boolStatus=$(curl -X 'GET' \
  "https://tsit-app1/api/v2/workItems/$case?versionNumber=0" \
  -H 'accept: application/json' \
  -H "Authorization: $apiKey" | jq '.isAutomated')
echo $boolStatus

name=$(curl -X 'GET' \
  "https://tsit-app1/api/v2/workItems/$case?versionNumber=0" \
  -H 'accept: application/json' \
  -H "Authorization: $apiKey" | jq '.name')
  echo $name

I tried
curl -X 'GET' \
  "https://tsit-app1/api/v2/workItems/$case?versionNumber=0" \
  -H 'accept: application/json' \
  -H "Authorization: $apiKey" | jq '"boolStatus=\(.isAutomated)", "name=\(.name)"'

but in echo i get

"boolStatus=true", 
"name=bla bla"

need to

echo $boolStatus 
true
echo $name 
bla bla

CodePudding user response:

One way would be to use the @sh string interpolation and then use your shell's eval.

Using the string interpolation would output something like:

boolStatus=true
name='abc'

which can then be fed to eval:

vars="$(curl ... | jq -r '@sh "boolStatus=\(.isAutomated)", @sh "name=\(.name)"')"
eval "$vars"

or explicitly output the line break:

jq -r '@sh "boolStatus=\(.isAutomated)\nname=\(.name)"'

Disclaimer: Note that this will evaluate any shell code and might open your system to malicious code (@sh escapes the values, but it's always a good idea to be aware of this).

CodePudding user response:

Use process substitution to allow two uses of read to read from the output of jq.

{ read boolStatus; read name; } < <(curl ... | jq -r '.isAutomated, .name')

(assuming the name does not contain any newlines).

At the very least, you can save the output to process with jq twice.

response=$(curl ...)
name=$(echo "$response" | jq -r .name)
boolStatus=$(echo "$response" | jq -r .isAutomated)
  • Related