Skip to content

Instantly share code, notes, and snippets.

@fvdm
Last active May 27, 2020 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fvdm/57649c15e7651b8f7b8d to your computer and use it in GitHub Desktop.
Save fvdm/57649c15e7651b8f7b8d to your computer and use it in GitHub Desktop.
#!/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 (https://github.com/fvdm)
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