How to curl and parse endpoint data with Bash?

1

I am trying to hit an endpoint http://myapp.com/health and get the version value. How would I do that? Note that I plan to run this script in TeamCity.

Response from http://myapp.com/health:

{
  "Status": "online",
  "Version": "1.23",
  "Environment": "Test"
}

icu222much

Posted 2019-12-05T18:46:52.877

Reputation: 597

Answers

1

jq method.

Try using jq like this:

curl -s 'http://myapp.com/health' | jq -r '.Version'

Create a Bash function.

Or you can create a Bash function called parse_json like this; found it on this StackOverflow answer here:

function parse_json()
{
    echo $1 | \
    sed -e 's/[{}]/''/g' | \
    sed -e 's/", "/'\",\"'/g' | \
    sed -e 's/" ,"/'\",\"'/g' | \
    sed -e 's/" , "/'\",\"'/g' | \
    sed -e 's/","/'\"---SEPERATOR---\"'/g' | \
    awk -F=':' -v RS='---SEPERATOR---' "\$1~/\"$2\"/ {print}" | \
    sed -e "s/\"$2\"://" | \
    tr -d "\n\t" | \
    sed -e 's/\\"/"/g' | \
    sed -e 's/\\\\/\\/g' | \
    sed -e 's/^[ \t]*//g' | \
    sed -e 's/^"//'  -e 's/"$//'
}

And it works like this; using inline JSON as a proof of concept:

parse_json '{
  "Status": "online",
  "Version": "1.23",
  "Environment": "Test"
}' Version

Output would be this:

1.23

awk method.

Or this honestly this awk method — from this answer — seems like the most cross-platform (at least on Unix-like systems); again using inline JSON as a proof of concept:

echo '{
  "Status": "online",
  "Version": "1.23",
  "Environment": "Test"
}' | awk 'BEGIN { FS="\""; RS="," }; { if ($2 == "Version") {print $4} }'

JakeGould

Posted 2019-12-05T18:46:52.877

Reputation: 38 217

I got the error: jq: command not found. Note that I plan to run this script in TeamCity so I'm not sure if I will have jq available in TeamCity., – icu222much – 2019-12-05T18:52:50.607

1@icu222much Well, if you can, you should install jq; excellent tool. But I just updated my answer with a pure Bash solution. – JakeGould – 2019-12-05T19:02:29.687