英文:
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 orval.data
isnull
I want to print a message "data not parsed correctly";
- when
val
is anobject
such as{"parm1":"****","data":"adfsdfsdaf"}
I want to print a message "data is null"
- when
val
isnull
.
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 orval.data
isnull
I want to print a message "data not parsed correctly"
- when
val
is anobject
such as{"parm1":"****","data":"adfsdfsdaf"}
I want to print a message "data is null"
- when
val
is annull
.
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论