【问题标题】:Unable to handle error in jq when value is not object当值不是对象时,无法处理 jq 中的错误
【发布时间】:2018-02-27 08:42:29
【问题描述】:

我正在尝试简化“try-catch”以检查“.data”元素的值是否包含下一个对象或简单字符串。最重要的是要消除报告给标准输出的错误(其他方式然后通用重定向到 /dev/null)

我目前正在使用这个:

    json2=`$APPFOLDER/jq -c '.data |= fromjson' <<< $json`

    if [[ ! $json2 ]]
      then
        json2=`$APPFOLDER/jq -c '.data |= { text: .}' <<< $json`
        json2=`$APPFOLDER/jq -c '.data |= { message: .}' <<< $json2`
    fi

为了将最终的简单字符串移动到 .data.message.text 元素中

但是没有更简单的方法吗? 当然,它会向标准输出报告错误,例如

jq: error (at <stdin>:1): Invalid numeric literal at line 1, column 9 (while parsing 'HTTP/1.1 403 Forbidden
Date: Tue, 27 Feb 2018 08:13:32 GMT
Server:
Connection: close
X-CorrelationID: Id-2c13955ae3bb6c3cc943460b 0
Content-Type: text/html

Access Denied')

我想试试

jq -r 'try .data |= fromjson catch "STRING"'

但它给了我错误:

jq: error: syntax error, unexpected catch, expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
try .data |= fromjson catch "STRING"                      
jq: 1 compile error
exit status 3

这里是示例消息:

{"correlationId":"2c13955ae3bb6c3cc943460b","leg":0,"tag":"sent","offset":167408,"len":178,"prev":{"page":{"file ":10481,"page":2},"record":1736},"data":"HTTP/1.1 403 禁止\r\n日期:2018 年 2 月 27 日星期二 08:13:32 GMT\r\n服务器: \r\n连接:关闭\r\nX-CorrelationID:Id-2c13955ae3bb6c3cc943460b 0\r\n内容类型:文本/html\r\n\r\n拒绝访问"}

【问题讨论】:

    标签: json try-catch posix jq


    【解决方案1】:

    我想试试

    jq -r 'try .data |= fromjson catch "STRING"'

    这是您必须使用括号帮助解析器的情况之一:

    jq -r 'try (.data |= fromjson) catch "STRING"'
    

    【讨论】:

    • 谢谢。我省略了这个选项。
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2020-04-30
    • 2020-05-03
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多