Jq

如何將我的 json 終端輸出中的 ’t’ 和 ’n’ 轉換為有用的東西?

  • September 30, 2019

我從 AWS 獲得了一些我想要清理的 JSON 日誌。他們看起來像這樣…

   {
       "ingestionTime": 1568961184459, 
       "timestamp": 1568961184430, 
       "message": "START RequestId: 0304cf0d-da16-4d01-b4de-da8d528144ac Version: $LATEST\n", 
       "eventId": "34989003600358241981666605756070906630881684882471780352", 
       "logStreamName": "2019/09/20/[$LATEST]71cac888c4a54d11b7e2c97108ad8ba1"
   }, 
   {
       "ingestionTime": 1568961199507, 
       "timestamp": 1568961184432, 
       "message": "2019-09-20T06:33:04.432Z\t0304cf0d-da16-4d01-b4de-da8d528144ac\tAttempting to subscribe John Doe (johndoe@gmail.com) to newsletter...\n", 
       "eventId": "34989003600402843472063667020546010973018230982964936704", 
       "logStreamName": "2019/09/20/[$LATEST]71cac888c4a54d11b7e2c97108ad8ba1"
   }, 

然後我讓他們做到這一點……通過使用……

{
 "ingestionTime": 1568961184459,
 "timestamp": 1568961184430,
 "message": "START RequestId: 0304cf0d-da16-4d01-b4de-da8d528144ac Version: $LATEST\n",
 "eventId": "34989003600358241981666605756070906630881684882471780352",
 "logStreamName": "2019/09/20/[$LATEST]71cac888c4a54d11b7e2c97108ad8ba1"
}
{
 "ingestionTime": 1568961199507,
 "timestamp": 1568961184432,
 "message": "2019-09-20T06:33:04.432Z\t0304cf0d-da16-4d01-b4de-da8d528144ac\tAttempting to subscribe John Doe (johndoe@gmail.com) to newsletter ...\n",
 "eventId": "34989003600402843472063667020546010973018230982964936704",
 "logStreamName": "2019/09/20/[$LATEST]71cac888c4a54d11b7e2c97108ad8ba1"
}

這個命令:aws logs filter-log-events --log-group-name /aws/lambda/$npm_package_name --region us-east-2 | jq '.events[]'

如果那些\t’s 實際上是選項卡會很好,並且\n最後可以刪除。或者為每個新選項卡將消息欄位分成幾個新行。

我該怎麼做?我真的不太了解bash。

jq預設輸出 JSON 編碼的字元串。

你想要原始 message字元串,使用-r--raw-output

jq -r .message file.json

(如果file.json是您顯示的 JSON 文件)。這將擴展該特定字元串中的製表符和換行符。

從不推薦在 bash 中解析 JSON,但是….

如果你可以按摩這條線:

   "message": "newline\n\nword\tword\tword", 

成為:

X_message="newline\n\nword\tword\tword"

那麼你就可以:

$ echo -e "$X_message"
newline

word    word    word

引用自:https://unix.stackexchange.com/questions/544532