Mentions légales du service

Skip to content
Snippets Groups Projects
Commit dce1969a authored by Brett Zamir's avatar Brett Zamir
Browse files

Allow avoiding autostart with optionally separate call to new public method, "evaluate"

parent 8ff538d6
No related branches found
No related tags found
No related merge requests found
......@@ -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];}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment