Permalink
Browse files

Continue to wrap results in an array. But if the caller says wrap: fa…

…lse, don't wrap.
  • Loading branch information...
1 parent 24a1fa5 commit b1427b164e840ed21883612bc1f91c695377610d @s3u committed Nov 18, 2011
Showing with 54 additions and 4 deletions.
  1. +17 −3 lib/jsonpath.js
  2. +1 −1 package.json
  3. +36 −0 test/test.arr.js
View
@@ -11,7 +11,7 @@ function jsonPath(obj, expr, arg) {
var P = {
resultType: arg && arg.resultType || "VALUE",
flatten: arg && arg.flatten || false,
- result: [],
+ wrap: (arg && arg.hasOwnProperty('wrap')) ? arg.wrap : true,
normalize: function(expr) {
if(cache[expr]) {
return cache[expr];
@@ -39,10 +39,22 @@ function jsonPath(obj, expr, arg) {
}
else {
if(_.isArray(v) && P.flatten) {
+ if(!P.result) P.result = [];
P.result = P.result.concat(v);
}
else {
- P.result[P.result.length] = v;
+ if(P.result) {
+ if(!_.isArray(P.result)) P.result = [P.result];
+ if(_.isArray(v) && P.flatten) {
+ P.result = P.result.concat(v);
+ }
+ else {
+ P.result[P.result.length] = v;
+ }
+ }
+ else {
+ P.result = v;
+ }
}
}
}
@@ -101,10 +113,12 @@ function jsonPath(obj, expr, arg) {
catch(e) { throw new SyntaxError("jsonPath: " + e.message + ": " + x.replace(/@/g, "_v").replace(/\^/g, "_a")); }
}
};
+ P.result = P.wrap === true ? [] : undefined;
var $ = obj;
if (expr && obj && (P.resultType == "VALUE" || P.resultType == "PATH")) {
P.trace(P.normalize(expr).replace(/^\$;/,""), obj, "$");
- return P.result.length ? P.result : false;
+ if(!_.isArray(P.result) && P.wrap) P.result = [P.result];
+ return P.result ? P.result : false;
}
}
View
@@ -16,7 +16,7 @@
"email": "mike@brevoort.com"
}
],
- "version": "0.8.3",
+ "version": "0.8.4",
"repository": {
"type": "git",
"url": "git://github.com/s3u/JSONPath.git"
View
@@ -0,0 +1,36 @@
+var jsonpath = require("../").eval,
+ testCase = require('nodeunit').testCase
+
+var json = {
+ "store": {
+ "book": { "category": "reference",
+ "author": "Nigel Rees",
+ "title": "Sayings of the Century",
+ "price": [8.95, 8.94, 8.93]
+ },
+ "books": [
+ { "category": "reference",
+ "author": "Nigel Rees",
+ "title": "Sayings of the Century",
+ "price": [8.95, 8.94, 8.93]
+ }
+ ]
+ }
+};
+
+
+module.exports = testCase({
+ "get single": function (test) {
+ var expected = json.store.book;
+ var result = jsonpath(json, "store.book", {flatten: true, wrap: false});
+ test.deepEqual(expected, result);
+ test.done();
+ },
+
+ "get arr": function (test) {
+ var expected = json.store.books;
+ var result = jsonpath(json, "store.books", {flatten: true, wrap: false});
+ test.deepEqual(expected, result);
+ test.done();
+ }
+});

0 comments on commit b1427b1

Please sign in to comment.