If we ran console.log(data)
on a object, Node.js automatically pretty prints (formats and colourises) the output
{
"this": {
"is": {
"a": {
"nested": {
"object": 123456
}
}
}
}
}
However, if we were to log our data with some sort of JSON logging library (i.e bunyan)
{hostname":"ExpensivePaperweight","pid":29946,"level":30,"this":{"is":{"a":{"nested":{"object":123456}}}},"msg":"","time":"2021-12-02T04:32:16.834Z","v":0}
Not very usable to us hey…
Bunyan has a formatter!
Bunyan actually comes with a CLI formatter
node program | npx bunyan
Enter jq
jq
is an awesome tool for exploring JSON data from within a command line; additionally it can also format lines of compact JSON, and pretty print it
./program | jq
{
"hostname": "ExpensivePaperweight",
"pid": 29946,
"level": 30,
"this": {
"is": {
"a": {
"nested": {
"object": 123456
}
}
}
},
"msg": "",
"time": "2021-12-02T04:32:16.834Z",
"v": 0
}
Not all of my lines are JSON!!!
If your code has non-JSON lines (i.e. If you ran yarn start
, it has overhead messages) you can use tail -n +LINE_NUMBER
to skip the first LINE_NUMBER - 1
items!
i.e. If your program has two lines of arbitrary data, and lines three and onwards are JSON-formatted strings, then you can run
./program | tail -n +3 | jq
Wings
For more readability, you can use a tool like bat
(improved version of cat
) to paginate / change colours.
$ yarn start | tail -n +3 | jq | bat -l json --paginate none
I would recommend using bat -l json
or bat -l json --pager none
(to not paginate)