dventi3
dventi3

Reputation: 991

Check if result is an empty string

I have a JSON file which I created using a jq command. The file is like this:

[
  {
    "description": "",
    "app": "hello-test-app"
  },
  {
    "description": "",
    "app": "hello-world-app"
  }
]

I would like to have just a simple if/else condition to check if the description is empty. I tried different approaches but none of them works!! I tried:

jq -c '.[]' input.json | while read i; do
description=$(echo $i | jq '.description')
if [[ "$description" == "" ]];
then
  echo "$description is empty"
fi
done

and with same code but this if/else;

if [[ -z "$description" ]];
then
  echo "$description is empty"
fi

Can someone help me?

Upvotes: 2

Views: 825

Answers (1)

kojiro
kojiro

Reputation: 77079

jq supports conditionals. No need to bring this back to bash (yet):

< foo jq -r '.[] | if .description == ""
                   then "description is empty"
                   else .description end'
description is empty
description is empty

If you insist on piping back to bash, here's what is happening:

jq -c '.[]' foo | while read i; do description=$(echo $i | jq '.description')
printf '%s\n' "$description"
done
""
""

You can see here that the expansion of $description is not empty. It is literally a pair of quotes each time.

There are several problems with piping to bash here -- the unquoted expansion of $i, repiping to jq and translating a pair of quotes into a empty string between two different programming languages. But I guess the simple answer is "just test if "$description" expands to a pair of quotes."

Testing quotes in bash means quoting your quotes:

if [[ $description = '""' ]]; then
    echo '$description expands to a pair of quotes'
fi

A better answer is, in my opinion, keep the work in jq.

Upvotes: 2

Related Questions