Skip to content

Instantly share code, notes, and snippets.

@fvdm fvdm/parsejson.js
Last active Jan 27, 2016

Embed
What would you like to do?
#!/usr/bin/env node
/*
USAGE: cat file.json | parsejson [OPTION] [PROPERTY]
Name: parsejson
Description: Parse JSON text to human-readable tree with syntax coloring.
Source: https://frankl.in/code/json-cli-parser-with-syntax-coloring
Author: Franklin van de Meent (https://frankl.in)
License: Unlicense / Public Domain
*/
var arg = process.argv.slice (2);
var color = true;
if (arg [0] === '-boring') {
arg = arg.slice (1);
color = false;
} else if (arg [0] === '-help') {
console.log ('USAGE: cat file.json | parsejson [OPTION] [PROPERTY]\n');
console.log (' -help This information');
console.log (' -boring Do not colorize the JSON output');
console.log (' property Only return this path from the tree.\n');
console.log ('Example:\n');
console.log (' echo \'{"dog":{"name":"Shadow"}}\' | parsejson dog name');
console.log (' -> \'Shadow\'\n');
process.exit ();
}
process.stdin.resume ();
process.stdin.setEncoding ('utf8');
process.stdin.on ('data', function (ch) {
var json = {};
var i;
try {
json = JSON.parse (ch);
if (arg.length) {
for (i = 0; i < arg.length; i++) {
json = json [arg [i]];
}
}
console.dir (json, { depth: null, colors: true });
} catch (e) {
console.log (e);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.