Setting jq output to a Bash Variable
88,257
Solution 1
Changed the code to this and it worked:
content=$(curl -s -X GET -H "Header:Value" http://127.0.0.1:8200/etc)
username=$( jq -r '.data.value' <<< "${content}" )
echo "${username}"
Solution 2
You can convert it to a one liner as:
username=$( curl -s -X GET -H "Header:Value" http://127.0.0.1:8200/etc | jq -r '.data.value' )
echo ${username}
Solution 3
This only works if you lose the "echo" on the second line.
content=$(curl -s -X GET -H "Header:Value" http://127.0.0.1:8200/etc)
username=$( echo jq -r '.data.value' <<< "${content}" )
echo ${username}
Related videos on Youtube
Author by
jymbo
Updated on September 18, 2022Comments
-
jymbo over 1 year
I'm using curl to get JSON back from a rest api like this:
content=$(curl -s -X GET -H "Header:Value" http://127.0.0.1:8200/etc) echo "${content}"| jq -r '.data.value'
which produces the value I need. However; when I change the above code to look like this:
content=$(curl -s -X GET -H "Header:Value" http://127.0.0.1:8200/etc) username=$(echo "${content}"| jq -r '.data.value') echo $username
Produces nothing. How can I change this so that the username variable gets assigned the output?
-
Kusalananda about 3 yearsConsider showing the contents of the
$content
variable. -
Kusalananda about 3 yearsI've closed this as the code in your self-answer is essentially the same as in the question. The code is therefore unlikely the reason why this failed for you. It's more likely that there is something strange going on with the actual data being passed from the web request (it's possibly being changed by
echo
, which may interpret back-slash sequences). We need more information about the actual data before being able to properly describe what's wrong and what to do about it.
-
-
Kusalananda about 3 yearsCould you please relate this to the question and say what issue it solves and how?
-
Francois Scheurer about 3 years@Kusalananda thx for the comment, I updated the answer accordingly.
-
Kusalananda about 3 yearsThis is just a repeat of an earlier answer. I edited that other answer so that it's correct. This answer still contains the errors (
echo
in the command substitution, and no quoting of$username
on last line). -
Kusalananda about 3 yearsThere is no indication as to why the user's code doesn't work. Your code here is functionally identical, at least at first glance. So, what's the difference that makes it work?