Treat curl return on Linux

0

I'm putting together a shellscript and sending a json file to a webservice, the return is as follows:

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

I'm trying, using Linux shell commands, throwing false in one variable o error message in another, but for not having space I'm 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 the message with awk, cut or another command?

    
asked by anonymous 05.04.2018 / 14:09

1 answer

0

One 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 cutter.

Using the rematch feature of sed, you replace the entire string in question only with the required excerpts, with a unique separator between them, as a semicolon:

> RESULT='{"success":false,"errorCode":3,"message":"Authenticity Token invalido"}';
> echo $RESULT | sed -r 's/\{"success":(true|false).*"message":"(.*)"\}/;/';
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 and . 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 read , all in one operation:

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

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

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