I want to be able to stream all the output data from when I run npm run start
into pretty JSON. The issue when using jq
is that some output is not JSON
is there any way to pretty-print JSON from an output stream where sometimes its text and sometimes it's JSON
Example id like
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node ./src/index.ts index.js`
helmet deprecated helmet.noCache is deprecated and will be removed in [11:11:55] Found 0 errors. Watching for file changes.
[{"caller": "RESOURCE ACCESS","token": "","msg": "xxx","statusCode": null,"level": "info","time": "xxx"},{"endpoint": "some endpoint","msg": "Initial endpoint","data": {"campaign_id": "xxx"},"level": "info","time": "xxx"},{"msg": "Request received","endpoint": "some other endpoint","method": "GET"}]
To be formatted in the terminal like
[nodemon] 1.19.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node ./src/index.ts index.js`
helmet deprecated helmet.noCache is deprecated and will be removed in [11:11:55] Found 0 errors. Watching for file changes.
[
{
"caller": "RESOURCE ACCESS",
"token": "",
"msg": "xxx",
"statusCode": null,
"level": "info",
"time": "xxx"
},
{
"endpoint": "some endpoint",
"msg": "Initial endpoint",
"data": {
"campaign_id": "xxx"
},
"level": "info",
"time": "xxx"
},
{
"msg": "Request received",
"endpoint": "some other endpoint",
"method": "GET"
}
]
CodePudding user response:
If your output may have JSON parts and non-JSON parts, you first need to find a way to isolate them in order to tell them apart.
For instance, if each item is on its own line (ie. all JSON parts are self-contained within their own line, then read in linewise as raw text using the --raw-input
(or -R
) option, check if you can convert them to JSON using the fromjson
builtin and the error suppression operator ?
, and if not (using the alternative operator //
) output the line as is using the --raw-output
(or -r
option):
… | jq --raw-input --raw-output 'fromjson? // .'