添加一个检查,以查找返回的值是否不是一个对象。

huangapple go评论73阅读模式
英文:

Adding a check to find if returned value is not an object

问题

I have a variable that retrieves value as below:

val = $(curl command ...)

val returns an object which looks as {"parm1":"****","data":"adfsdfsdaf"}

I want to add a validation for two conditions:

  • val is either an object or
  • val.data is null

I want to print a message "data not parsed correctly";

  • when val is an object such as {"parm1":"****","data":"adfsdfsdaf"}

I want to print a message "data is null"

  • when val is null.

I have written below logic for it but it is not looking correct:

if [[ ${val} == null ]]; then
  echo "data not parsed correctly"
  exit 1

The correct value of val is adfsdfsdaf when the script should not exit.

英文:

I have a variable that retrieves value as below:

val = $(curl command ...)

val returns an object which looks as {"parm1":"****","data":"adfsdfsdaf"}

I want to add a validation for two conditions:

  • val is either an object or
  • val.data is null

I want to print a message "data not parsed correctly"

  • when val is an object such as {"parm1":"****","data":"adfsdfsdaf"}

I want to print a message "data is null"

  • when val is an null.

I have written below logic for it but it is not looking correct:

if [[ ${val} == null ]]; then
  echo "data not parsed correctly"
  exit 1

The correct value of val is adfsdfsdaf when the script should not exit.

答案1

得分: 3

if val=$(curl ... \
         | jq 'try 
                 if .data != null 
                   then . 
                   else ("is null" | halt_error) 
                 end 
               catch
                 ("not an object" | halt_error)
            ' 2>&1
        )
then
    do_something_with_valid "$val"
else
    echo "error: $val" >&2
    exit 1
fi
英文:

With [tag:jq]

if val=$(curl ... \
         | jq 'try 
                 if .data != null 
                   then . 
                   else ("is null" | halt_error) 
                 end 
               catch
                 ("not an object" | halt_error)
            ' 2>&1
        )
then
    do_something_with_valid "$val"
else
    echo "error: $val" >&2
    exit 1
fi

huangapple
  • 本文由 发表于 2023年7月14日 04:51:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定