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

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

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

问题

I have a variable that retrieves value as below:

  1. 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:

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

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

英文:

I have a variable that retrieves value as below:

  1. 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:

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

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

答案1

得分: 3

  1. if val=$(curl ... \
  2. | jq 'try
  3. if .data != null
  4. then .
  5. else ("is null" | halt_error)
  6. end
  7. catch
  8. ("not an object" | halt_error)
  9. ' 2>&1
  10. )
  11. then
  12. do_something_with_valid "$val"
  13. else
  14. echo "error: $val" >&2
  15. exit 1
  16. fi
英文:

With [tag:jq]

  1. if val=$(curl ... \
  2. | jq 'try
  3. if .data != null
  4. then .
  5. else ("is null" | halt_error)
  6. end
  7. catch
  8. ("not an object" | halt_error)
  9. ' 2>&1
  10. )
  11. then
  12. do_something_with_valid "$val"
  13. else
  14. echo "error: $val" >&2
  15. exit 1
  16. 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:

确定