3

我在验证 json 字符串时遇到问题。我正在使用下面的代码

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

这不适用于json_string={"fruit":{"name":"app. 这仍然成功显示解析的 JSON,并且得到了除 false/null 以外的其他内容,因为 json 字符串不完整。

4

1 回答 1

4

显然这是中的问题之一jq-1.5。没有相应关闭字符的未终止对象/数组被视为有效对象并被解析器接受。可以复制jq-1.5,但固定在jq-1.6

jq-1.6

jq -e . <<< '{"fruit":{"name":"app'
parse error: Unfinished string at EOF at line 2, column 0
echo $?
4

下面的最小可重现示例,在 1.6 中再次得到很好的处理,但在 1.5 中不会引发错误

jq -e . <<< '{'
parse error: Unfinished JSON term at EOF at line 2, column 0
jq -e . <<< '['
parse error: Unfinished JSON term at EOF at line 2, column 0

建议升级以jq-1.6使这项工作!

于 2020-09-04T10:42:54.120 回答