Home > Software design >  check if the json file string is empty in bash script
check if the json file string is empty in bash script

Time:11-02

HI my Json file is as follows:

{
    "num_sensor" : 1,
    "J2" : {"B" : "sensor0", "A" : "sensor1", "D" : "sensor2" , "C" : "sensor3"},
    "J1" : {"B" : "", "A" : "sensor5", "D" : "sensor6" , "C" : "sensor7"} 
}

I tried the following to check J1.B is empty:

s=`jq '.J1.B' ~/package/sensor_data.json`

With the following methods:

if [[ $s = """" ]];
then
echo "empty"
else
echo "not_empty"
echo "$s"
fi

jq -r '.[] | if .J1.B == ""
                   then "description is empty"
                   else .J1.B end' ~/package/sensor_data.json

k=`jq '.J1.B' ~/package/sensor_data.json select (.!=null)`
echo "$k"

if [ -z "$s" ]
then
      echo "\$var is empty"
      
else
      echo "\$var is NOT empty"
      echo "$s"
fi

None of them work. Everything gives me non-empty and

jq -r '.[] | if .J1.B == ""
                   then "description is empty"
                   else .J1.B end' ~/package/sensor_data.json

gives me Error as:

 Cannot index number with string "J1"

Can you please let me know how I can check empty string of json file in bash script?

CodePudding user response:

Remove leading and trailing spaces (if any) and test for empty string

echo '{"J1" : {"B" : ""} }' | jq 'if((.J1.B | gsub("^\\s |\\s $";"")) == "") then "empty" else .J1.B end'
"empty"

echo '{"J1" : {"B" : "  "} }' | jq 'if((.J1.B | gsub("^\\s |\\s $";"")) == "") then "empty" else .J1.B end'
"empty"

echo '{"J1" : {"B" : " a"} }' | jq 'if((.J1.B | gsub("^\\s |\\s $";"")) == "") then "empty" else .J1.B end'
" a"

CodePudding user response:

There are a couple of things going on here. The first thing to note is that this expression is returning "", not an empty string. That is, it's returing a string with 2 double quotes:

$ jq .J1.B json
""

And so, this expression yields nothing:

$ s=$(jq .J1.B json)
$  [ -z "$s" ]  && echo empty

empty is NOT printed because s is not empty. It actually contains the string "".

There are a couple ways of addressing this. My preferred method is just to pass the -r (raw) flag to jq:

$ s=$(jq  -r  .J1.B json) ;  [ -z "$s" ]  && echo empty
empty

Here's another approach: Compare to double quotes:

$ s=$(jq  .J1.B json) ; [ "$s" == '""' ]  && echo empty
empty

Above, you can see a quoted the string with single quotes. Using """" is a bad practice - since that evaluates to an empty string next to another empty string (still of length 0).

$ a=""""; echo ${#a}
0
  • Related