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}
Share:
88,257

Related videos on Youtube

jymbo
Author by

jymbo

Updated on September 18, 2022

Comments

  • jymbo
    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
      Kusalananda about 3 years
      Consider showing the contents of the $content variable.
    • Kusalananda
      Kusalananda about 3 years
      I'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
    Kusalananda about 3 years
    Could you please relate this to the question and say what issue it solves and how?
  • Francois Scheurer
    Francois Scheurer about 3 years
    @Kusalananda thx for the comment, I updated the answer accordingly.
  • Kusalananda
    Kusalananda about 3 years
    This 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
    Kusalananda about 3 years
    There 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?