Reddy SK
Reddy SK

Reputation: 1374

Unable to handle error in jq when value is not object

I am trying to simplify "try-catch" for checking if value of ".data" element contain next object or simple string. And on top of that want to eliminate errors reported to standard output (other way then generic redirection to /dev/null)

I am using currently this:

    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

in order to move eventual simple string into .data.message.text element

But isn't there simplier way how to do it? Of course it reports error to standard output like

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')

I wanted to try

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

but it is giving me error:

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

here is sample message:

{"correlationId":"2c13955ae3bb6c3cc943460b","leg":0,"tag":"sent","offset":167408,"len":178,"prev":{"page":{"file":10481,"page":2},"record":1736},"data":"HTTP/1.1 403 Forbidden\r\nDate: Tue, 27 Feb 2018 08:13:32 GMT\r\nServer: \r\nConnection: close\r\nX-CorrelationID: Id-2c13955ae3bb6c3cc943460b 0\r\nContent-Type: text/html\r\n\r\nAccess Denied"}

Upvotes: 0

Views: 3331

Answers (1)

peak
peak

Reputation: 116670

I wanted to try

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

This is one of the occasions when you have to help the parser by using parentheses:

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

Upvotes: 2

Related Questions