Skip to content

Instantly share code, notes, and snippets.

@robomatic
Last active April 18, 2016 20:12
Show Gist options
  • Save robomatic/45f7bd7eac91dc780418ce8c8cdf8da9 to your computer and use it in GitHub Desktop.
Save robomatic/45f7bd7eac91dc780418ce8c8cdf8da9 to your computer and use it in GitHub Desktop.
NodeJS JSON prettifier for REST piping on the console
'use strict';
/**
* JSON prettifier
*
* as a general prettifier `node jsonpr.js '{"this":"is","json":"prettifier"}'`
* as a stream reader `echo '{"some":"JSON"}' | node jsonpr.js`
*/
process.stdin.setEncoding('utf8');
let stdin = process.openStdin();
let json = process.argv[2];
let spaces = 4;
if (process.argv[3]) {
spaces = parseInt(process.argv[3]);
}
function logJSONString(json) {
let jsonObj = JSON.parse(json);
let jsonString = JSON.stringify(jsonObj, null, spaces);
console.log(jsonString);
}
if (json) {
logJSONString(json);
process.exit();
}
stdin.on('data', function(chunk) {
logJSONString(chunk);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment