Permalink
Browse files

Support using a single JSON array as input

  • Loading branch information...
1 parent 3992313 commit 83825878836b56bd2bc3042f032792ac97558596 @andreyvit andreyvit committed Dec 27, 2011
Showing with 17 additions and 0 deletions.
  1. +3 −0 README.md
  2. +14 −0 lib/jsonCommand.js
View
3 README.md
@@ -62,6 +62,8 @@ please note that the last two examples require you to enter your username and pa
new.key=old_key move old_key to new.key in output object
+ -a input object is an array, process each element separately
+
-c "js conditional" js conditional to be run in the context of each object that determines whether an object is printed
-C print the output fields as tab delimited columns in the order specified by fields
@@ -86,6 +88,7 @@ like -e and foo=bar allow for transforming object structure.
e.g. { obj1 : body }{ obj2 : body }
* file separated json objects.
e.g. cat files/* | json
+* when using -a, a single JSON array
## Order of operations
View
14 lib/jsonCommand.js
@@ -18,6 +18,7 @@ JSON.Command = function(args) {
this.headerPassthrough = false;
this.columnOutput = false;
this.useObject = null;
+ this.inputIsArray = false;
this.conditionals = [];
this.executables = [];
@@ -43,6 +44,7 @@ JSON.Command.prototype.printhelp = function() {
sys.puts(" -d print debugging output including exception messages\n");
sys.puts(" -o object.path specify the path to an array to be iterated on\n");
sys.puts(" new.key=old_key move old_key to new.key in output object\n");
+ sys.puts(" -a input object is an array, process each element separately\n");
sys.puts(" -c \"js conditional\" js conditional to be run in the context of each object");
sys.puts(" that determines whether an object is printed\n");
sys.puts(" -C print the output fields as tab delimited columns in");
@@ -140,6 +142,9 @@ JSON.Command.prototype.processArgs = function processArgs(args) {
case "-o": // use object
this.useObject = a.shift();
break;
+ case "-a": // array
+ this.inputIsArray = true;
+ break;
case "-i": // use sys.inspect
this.inspectOutput = true;
break;
@@ -339,6 +344,13 @@ JSON.Command.prototype.processObjects = function(objects) {
this.printex(ex);
}
+ if (this.inputIsArray && objects && objects.length > 0 && typeof(objects[0]) == 'string') {
+ var trimmed = objects[0].trim();
+ if (trimmed.length > 0 && trimmed[0] == '[') {
+ objects = JSON.parse(objects[0]);
+ }
+ }
+
try {
for (var i = 0; (i < (objects.length)); i++) {
// if there's no object, there's nothing to do
@@ -409,6 +421,8 @@ JSON.Command.prototype.processInput = function() {
this.stdin.on("data", function(chunk) {
this.jsonC.buffer += chunk;
+ if (this.jsonC.inputIsArray) return;
+
var objects = null;
if (this.jsonC.buffer.match(/\n/g) ||
this.jsonC.buffer.match(/\r\n/g) ||

0 comments on commit 8382587

Please sign in to comment.