How to parse json response in the shell script?
If you are going to be using any more complicated json from the shell and you can install additional software, jq is going to be your friend.
So, for example, if you want to just extract the error message if present, then you can do this:
$ echo '{"error": "Some Error"}' | jq ".error""Some Error"
If you try this on the success case, it will do:
$echo '{"success": "Yay"}' | jq ".error"null
The main advantage of the tool is simply that it fully understands json. So, no need for concern over corner cases and whatnot.
#!/bin/bashIFS= read -d '' DATA < temp.txt ## Imitates your DATA=$(wget ...). Just replace it.while IFS=\" read -ra LINE; do case "${LINE[1]}" in error) # ERROR_MSG=${LINE[3]} printf -v ERROR_MSG '%b' "${LINE[3]}" ;; success) # SUCCESS_MSG=${LINE[3]} printf -v SUCCESS_MSG '%b' "${LINE[3]}" ;; esacdone <<< "$DATA"echo "$ERROR_MSG|$SUCCESS_MSG" ## Shows: error_message|success_message
* %b
expands backslash escape sequences in the corresponding argument.
Update as I didn't really get the question at first. It should simply be:
IFS=\" read __ KEY __ MESSAGE __ <<< "$DATA"[[ $KEY == success ]] ## Gives $? = 0 if true or else 1 if false.
And you can examine it further:
case "$KEY" insuccess) echo "Success message: $MESSAGE" exit 0 ;;error) echo "Error message: $MESSAGE" exit 1 ;;esac
Of course similar obvious tests can be done with it:
if [[ $KEY == success ]]; then echo "It was successful."else echo "It wasn't."fi
From your last comment it can be simply done as
IFS=\" read __ KEY __ MESSAGE __ <<< "$DATA"echo "$DATA" ## Your really need to show $DATA and not $MESSAGE right?[[ $KEY == success ]]exit ## Exits with code based from current $?. Not necessary if you're on the last line of the script.
You probably already have python installed, which has json parsing in the standard library. Python is not a great language for one-liners in shell scripts, but here is one way to use it:
#!/bin/bashDATA=$(wget -O - -q -t 1 http://localhost:8080/test_beat)if python -c 'import json, sysexit(1 if "error" in json.loads(sys.stdin.read()) else 0)' <<<"$DATA"then echo "SUCCESS: $DATA"else echo "ERROR: $DATA" exit 1fi