Last active
April 18, 2016 20:12
-
-
Save robomatic/45f7bd7eac91dc780418ce8c8cdf8da9 to your computer and use it in GitHub Desktop.
NodeJS JSON prettifier for REST piping on the console
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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