我从 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 ([email protected]) 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 ([email protected]) 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
如果这些实际上是选项卡,并且\n
最后的 可以被删除,那就太好了。或者将每个新选项卡的消息字段分成几个新行。
我该怎么做?我对 bash 的了解还不够。
答案1
jq
默认输出 JSON 编码的字符串。
你想要生的 message
字符串,使用-r
或--raw-output
:
jq -r .message file.json
(如果file.json
是您显示的 JSON 文档)。这将扩展该特定字符串中的制表符和换行符。
答案2
从来不建议在 bash 中解析 JSON,但是......
如果你可以按摩这条线:
"message": "newline\n\nword\tword\tword",
成为:
X_message="newline\n\nword\tword\tword"
然后你可以:
$ echo -e "$X_message"
newline
word word word