Treat Curl return on Linux

Asked

Viewed 674 times

2

I am mounting a shellscript and sends a json file to a webservice, the return is as follows:

{"success":false,"errorCode":3,"message":"Authenticity Token invalido"}

I am tempted, using Linux commands (shell script), to play the false in one variable o the error message in another, but for not having space I am not getting with awk, as follows:

SUCCESS=$(echo $RESULT | awk -F ':' '/success/ {print $2}')
ERROR=$(echo $RESULT | awk -F ':"' '/message/ {print $2}')

The return of both, respectively, is:

false,"errorCode"
Authenticity Token invalido"}

How to return only true or false and message with awk, cut or other command?

  • To return true or false I managed to run awk twice: SUCCESS=$(echo $RESULT | awk -F ':' '/Success/ {print $2}' | awk -F ',' '/false|true/ {print $1}') .

2 answers

2

A way to solve this kind of thing with bash is to use regular expressions to "clean" the return string and add separators that can then be treated with a cutting tool.

Using the functionality of rematch sed, you replace the entire string in question only with the necessary snippets, with a unique separator between them, such as semicolon:

> RESULT='{"success":false,"errorCode":3,"message":"Authenticity Token invalido"}';
> echo $RESULT | sed -r 's/\{"success":(true|false).*"message":"(.*)"\}/\1;\2/';
false;Authenticity Token invalido

Using the parentheses in the regular expression, the content they surround is passed to the numeric variables of rematch, in the case \1 and \2. So you’re replacing the entire string with these two variables, separated by the semicolon.

With this output string, you can assign it to different variables by setting the shell separator character equal to the chosen semicolon, and use the read, all in one operation:

> IFS=';' read SUCCESS MESSAGE <<< $(echo $RESULT | sed -r 's/\{"success":(true|false).*"message":"(.*)"\}/\1;\2/');
> echo $SUCCESS;
false
> echo $MESSAGE;
Authenticity Token invalido

If you prefer you can of course run two sed as you asked in the question:

> SUCCESS=$(echo $RESULT | sed -r 's/\{"success":(true|false).*/\1/');
> MESSAGE=$(echo $RESULT | sed -r 's/.*"message":"(.*)"\}/\1/');
> echo $SUCCESS;
false
> $MESSAGE;
Authenticity Token invalido

1

The ideal in this type of problem is to use tools that recognize the JSON format.

Example with the jq

$ S=$(jq -r .success <<< $RESULT)
$ M=$(jq -r .message <<< $RESULT)
$ echo $M
Authenticity Token invalido

Browser other questions tagged

You are not signed in. Login or sign up in order to post.