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} }'
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 havejq
available in TeamCity., – icu222much – 2019-12-05T18:52:50.6071@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