skip to Main Content

I have a logfile with entries like this:

{"@timestamp":"2024-02-28T10:21:51.939Z", "log.level":"info", "msg": "done"}

I want to convert this json into something like this:

2024-02-28T10:21:51.939Z - info - done

This is the output I get from my shell commands:

$ msg='{"@timestamp":"2024-02-28T10:21:51.939Z", "log.level":"info", "msg": "done"}'

$ echo $msg | jq -r '"(.["log.level"])"'
jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
"(.["log.level"])"     
jq: 1 compile error

$ echo $msg | jq -r '"(.msg)"'
done

$ echo $msg | jq -r '"(.["@timestamp"])"'
jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
"(.["@timestamp"])"     
jq: 1 compile error

$ echo $msg | jq -r '"(.@timestamp)"'
jq: error: syntax error, unexpected QQSTRING_INTERP_END, expecting QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
"(.@timestamp)"              
jq: error: try .["field"] instead of .field for unusually named fields at <top-level>, line 1:
"(.@timestamp)"   
jq: 2 compile errors

I’m using bash on Ubuntu. jq-1.6

2

Answers


  1. Chosen as BEST ANSWER

    Ok, I fixed my own problem. In contrast to the manual, you don't have to escape the quotes.

    $ echo $msg | jq -r '"(.["@timestamp"])"'
    2024-02-28T10:21:51.939Z
    
    $ echo $msg | jq -r '"(.["log.level"])"'
    info
    

  2. Here are some ways:

    # if you don't like working with blackslashes
    echo $msg | jq -r '[.["@timestamp","log.level","msg"]]|join(" - ")'         
    
    # if you want all the values (which in your case you do)
    echo $msg | jq -r 'values|join(" - ")'
    
    # to_entries if you want to manipulate value
    echo $msg | jq -r 'to_entries|map(.value)|join(" - ")'
    echo $msg | jq -r 'to_entries|map(.value|ascii_upcase)|join(" - ")'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search