diff --git a/lib/jsonpath.js b/lib/jsonpath.js index 7ee5abfd3b046e674611eb9062845d08f86ee50a..7b96d3b6ce9240b40fc4d9dc5dabb28745fb5e49 100644 --- a/lib/jsonpath.js +++ b/lib/jsonpath.js @@ -37,25 +37,34 @@ function JSONPath (opts, obj, expr) { if (!(this instanceof JSONPath)) { // Make "new" optional return new JSONPath(opts, obj, expr); } - this.obj = obj; - var self = this; - var resultType = (opts && opts.resultType.toLowerCase()) || 'value'; - var flatten = (opts && opts.flatten) || false; - var wrap = (opts && opts.hasOwnProperty('wrap')) ? opts.wrap : true; - this.sandbox = (opts && opts.sandbox) ? opts.sandbox : {}; + opts = opts || {}; + this.resultType = (opts.resultType && opts.resultType.toLowerCase()) || 'value'; + this.flatten = opts.flatten || false; + this.wrap = opts.hasOwnProperty('wrap') ? opts.wrap : true; + this.sandbox = opts.sandbox || {}; + + if (opts.autostart !== false) { + return this.evaluate(obj, expr); + } +} + +// PUBLIC METHODS - if (expr && obj && (resultType === 'value' || resultType === 'path')) { +JSONPath.prototype.evaluate = function (obj, expr) { + var self = this; + this.obj = obj; + if (expr && obj && (this.resultType === 'value' || this.resultType === 'path')) { var exprList = this._normalize(expr); if (exprList[0] === '$' && exprList.length > 1) {exprList.shift();} var result = this._trace(exprList, obj, ['$']); result = result.filter(function (ea) { return ea && !ea.isParentSelector; }); - if (!result.length) {return wrap ? [] : false;} - if (result.length === 1 && !wrap && !Array.isArray(result[0].value)) {return result[0][resultType] || false;} + if (!result.length) {return this.wrap ? [] : false;} + if (result.length === 1 && !this.wrap && !Array.isArray(result[0].value)) {return result[0][this.resultType] || false;} return result.reduce(function (result, ea) { - var valOrPath = ea[resultType]; - if (resultType === 'path') {valOrPath = self._asPath(valOrPath);} - if (flatten && Array.isArray(valOrPath)) { + var valOrPath = ea[self.resultType]; + if (self.resultType === 'path') {valOrPath = self._asPath(valOrPath);} + if (self.flatten && Array.isArray(valOrPath)) { result = result.concat(valOrPath); } else { result.push(valOrPath); @@ -63,7 +72,9 @@ function JSONPath (opts, obj, expr) { return result; }, []); } -} +}; + +// PRIVATE METHODS JSONPath.prototype._normalize = function (expr) { if (cache[expr]) {return cache[expr];}