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.我可以用ofc判断字符串中的一些关键字,比如error f.e.,但我正在寻找一个更可靠的选项,例如,我从jq那里得到了true/false1/0.

更新:

我有这个:

 result=$(some command)

from which the result is the string error services-migration/foobar: Not found: services-migration/foobar

And then the if statement:

 if jq -e . >/dev/null 2>&1 <<<"$result"; then
    echo "it catches it"
 else
    echo "it doesn't catch it"
 fi

And it always ends up in the else clause.

推荐答案

从手册中:

-e / --exit-status:

如果最后一个输出值既不是false也不是null,则将jq的退出状态设置为0;如果最后一个输出值既不是false也不是null,则将jq的退出状态设置为1;如果从未生成有效结果,则将jq的退出状态设置为4.通常,如果存在任何使用问题或系统错误,jq将以2退出,如果存在jq程序编译错误,则以3退出,如果jq程序运行,则以0退出.

So you can use:

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

事实上,如果您不关心区分不同类型的错误,那么您可能会失go -eswitch .在这种情况下,任何被认为有效的JSON(包括FALSE/NULL)都将被过滤成功解析,并且程序将成功终止,因此将跟随第if分支.

Json相关问答推荐

最新版本的Deneb在数据溢出时不支持滚动

我如何知道TJSONNumber是double还是double?

如何使用GoFr返回XML响应?

如何创建生成两个不同对象的JSON数组的SQL查询?

使用JQ将JSON输出转换为CSV复杂 struct

PowerShell - 将 json 添加到文件内容

JOLT转换并向输出添加新数组

如何编写 jolt 规范以将不同的对象转换为数组

使用 jolt 将对象数组转换为数组

打印与 JSON 和 PowerShell 中的模式匹配的子项的父项名称

通过 xslt 将内部 json 转换为 xml 时遇到问题

如何在 Android Studio 中将 List 字段作为空列表[]返回?

JOLT 在 struct 体中间添加一个 JSON 字段

从 HttpResponse 获取 json

消息通知产生此内容无法显示

如何按键查找特定的 JSON 值?

Swift :将 struct 转换为 JSON?

无法将空值放入 JSON 对象

如何从 MySQL 中检索 JSON 数据?

如何使用 Jackson 的 objectMapper 反序列化接口字段?