Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active November 29, 2023 02:47
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save kristopherjohnson/5065599 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/5065599 to your computer and use it in GitHub Desktop.
Read JSON from standard input and writes formatted JSON to standard output. Requires Node.js.
#!/usr/bin/env node
// Reads JSON from stdin and writes equivalent
// nicely-formatted JSON to stdout.
var stdin = process.stdin,
stdout = process.stdout,
inputChunks = [];
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
inputChunks.push(chunk);
});
stdin.on('end', function () {
var inputJSON = inputChunks.join(),
parsedData = JSON.parse(inputJSON),
outputJSON = JSON.stringify(parsedData, null, ' ');
stdout.write(outputJSON);
stdout.write('\n');
});
@danthegoodman
Copy link

Here's a oneliner that does the same thing (at least in mac and linux land, not sure about windows):

node -p 'JSON.stringify(JSON.parse(fs.readFileSync(0)),null,2)'

notably, JSON.parse can work off of a buffer and fs.readFileSync(0) reads the zero file descriptor, which is standard input.
Then, node -p is a way to execute and log the output from a statement. You could also write it with a node -e 'console.log(...)' if you would rather be in control of when or how the logging happens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment