问题描述
取消服务时,我需要捕捉一个错误.响应可以是null
,类似
I need to catch an error when lifting a service. The response can be null
, a string error message like
error services-migration/foobar: Not found: services-migration/foobar
或一切正常时的有效JSON.我想知道jq
是否有一种方法可以简单地检查所提供的字符串是否为有效的JSON.我可以经常检查某些关键字的字符串,例如error
f.e.,但是我正在寻找一个更可靠的选项,例如.我从jq得到true/false
或1/0
.我正在浏览jq
的文档以及关于SO的一些问题,但所有内容都是关于从JSON查找和挑选键值的,但与简单地验证字符串无关.
or a valid JSON when everything is fine. I was wondering if there is a way with jq
to simply check if the provided string is a valid JSON. I could ofc check the string for some keywords like error
f.e., but I'm looking for a more robust option, where eg. I get a true/false
or 1/0
from jq.I was looking through the docs of jq
and also some questions here on SO but everything was about finding and picking out key-values from a JSON, but nothing about simply validating a string.
更新:
我有这个:
result=$(some command)
的结果是字符串error services-migration/foobar: Not found: services-migration/foobar
然后是if语句:
if jq -e . >/dev/null 2>&1 <<<"$result"; then
echo "it catches it"
else
echo "it doesn't catch it"
fi
它总是以else
子句结尾.
推荐答案
摘自手册:
如果最后一个输出值既不是false也不是null,则将jq的退出状态设置为0;如果最后一个输出值是false或null则将jq的退出状态设置为1;或者,如果没有产生有效结果,则将其设置为4.通常,如果出现使用问题或系统错误,jq退出时为2;如果出现jq程序编译错误,则退出3;如果运行jq程序,则退出0.
Sets the exit status of jq to 0 if the last output values was neither false nor null, 1 if the last output value was either false or null, or 4 if no valid result was ever produced. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran.
因此您可以使用:
if jq -e . >/dev/null 2>&1 <<<"$json_string"; then
echo "Parsed JSON successfully and got something other than false/null"
else
echo "Failed to parse JSON, or got false/null"
fi
实际上,如果您不关心区分不同类型的错误,那么您可以丢掉-e
开关.在这种情况下,筛选器.
将成功解析任何被视为有效JSON(包括false/null)的内容,并且程序将成功终止,因此将遵循if
分支.
In fact, if you don't care about distinguishing between the different types of error, then you can just lose the -e
switch. In this case, anything considered to be valid JSON (including false/null) will be parsed successfully by the filter .
and the program will terminate successfully, so the if
branch will be followed.
这篇关于使用jq检查字符串是否是有效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!