Last Updated: March 07, 2016
·
10.11K
· dpashkevich

Pretty print JSON from command line with NodeJS

Inspired by this protip: Commandline JSON Pretty Print everywhere.

I was pretty sure it can be done in less code in NodeJS since JSON format is native to the language but the "one-liner" I came up with so far looks pretty ugly:

echo '{"hello": 1, "foo": "bar"}' | xargs -0 node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 2))"

The esoteric goal was to not use any external modules :)

Since NodeJS deals with stdin asynchronously and the stream is paused by default, I figured it's shorter to just use some help from the good ol' xargs to convert stdin to arguments.

Anybody has a better solution? :)

2 Responses
Add your response

It would be nice to do something like this:

echo '{"hello": 1, "foo": "bar"}' | node -e "process.stdin.pipe(console.dir)"

Maybe with streams2

over 1 year ago ·

Save this on your PATH. Read the first arg as the file or read stdin. When piping to it, /dev/stdin will look like a file and get and EOF when it's done... assuming your JSON doesn't overrun the memory, it should work.

#!/usr/bin/env node
var args = process.argv.splice( /node$/.test(process.argv[0]) ? 2 : 1 );
console.log(
    JSON.stringify(
        JSON.parse(
            require('fs') .readFileSync(
                args.length > 0 ? args[0] : "/dev/stdin"
            )
        ), null, 4)
);
over 1 year ago ·