Skip to content

Instantly share code, notes, and snippets.

@rctay
Forked from kristopherjohnson/formatjson.js
Last active August 29, 2015 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rctay/25c62af2dfb52d7b2335 to your computer and use it in GitHub Desktop.
Save rctay/25c62af2dfb52d7b2335 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
// Reads JSON from stdin, and runs a JSONPath expression from the command-line on it.
//
// eg.
// $ npm install # install dependencies
// $ echo '{"store": {"book":[{"category":"fiction"}]}}' | node jsonpath.js '$.store.book[0].category'
// fiction
var stdin = process.stdin,
stdout = process.stdout,
inputChunks = [];
var jsonPath = require('JSONPath');
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);
var result = jsonPath.eval(parsedData, process.argv[2], {wrap: false})
stdout.write(result.toString()); // could be a number
stdout.write('\n');
});
{
"dependencies": {
"JSONPath": "0.10.x"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment