lundi 9 octobre 2017

bash JSON with jq - how to check for empty JSON members?

I want to detect an error depending on an error message JSON field being empty or non-empty . I am using jq to slice out the member, but then have massive trouble evaluating it in my bash "if".

I have a json file referenced by my variable $input which does have an errMsg member, but as an empty string (note that my CLI prompt is ~$) :

~$ echo $(jq "." $input)
{ "projectCode": "145", "fullCode": "1", "errMsg": "" }

retrieving the errMsg field in this case properly yields an empty string:

~$ err=$(jq ".errMsg" $input)
~$ echo $err
""

Problem : testing that variable seems impossible :

~$ if [ $err = "" ]; then echo EMPTY; else echo CONTENT; fi 
CONTENT

I excpected the EMPTY as $err just showed "". Checking other way around:

~$ if [ $err != "" ]; then echo EMPTY; else echo CONTENT; fi
EMPTY 

so $err is apparently not "", even though echo $err yields "" ? How can that be ? What bash feature am I missing here ?

Anyway, lets try that with a non-empty json (after changing the $input content):

~$ echo $(jq "." $input)
{ "projectCode": "145", "fullCode": "1", "errMsg": "not empty" }
~$ echo $err
"not empty"

~$ if [ $err != "" ]; then echo EMPTY; else echo CONTENT; fi
bash: syntax error near unexpected token `then'

okay, then masking like this :

~$ if [ "$err" != "" ]; then echo EMPTY; else echo CONTENT; fi
bash: syntax error near unexpected token `then'

I guess it finds a second token after "not" and doesnt like it. After much research i find this truly unreadable solution that seems to work:

~$ val=$(sed "s/^\(\"\)\(.*\)\1\$/\2/g" <<<"$err" | sed -e 's/\s.*$//')
~$ if [ "$val" = "" ]; then echo "NO ERROR"; else echo "ERROR"; fi
NO ERROR

it also works for non-empty errMsg members. Please, there MUST be a simple and elegant solution to this.

Aucun commentaire:

Enregistrer un commentaire