check if the json file string is empty in bash script

Issue

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?

Solution

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"

Answered By – LMC

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published