Mentions légales du service

Skip to content
Snippets Groups Projects
Commit a3252af7 authored by Subbu Allamaraju's avatar Subbu Allamaraju
Browse files

Merge pull request #28 from brettz9/master

Remove "with", strict mode, rmv unused vars, and other JSLint-inspired changes
parents 3133eda3 a09efe3d
No related branches found
No related tags found
No related merge requests found
/*global module, exports, require*/
/*jslint vars:true, evil:true*/
/* JSONPath 0.8.0 - XPath for JSON /* JSONPath 0.8.0 - XPath for JSON
* *
* Copyright (c) 2007 Stefan Goessner (goessner.net) * Copyright (c) 2007 Stefan Goessner (goessner.net)
* Licensed under the MIT (MIT-LICENSE.txt) licence. * Licensed under the MIT (MIT-LICENSE.txt) licence.
*/ */
var isNode = false; (function(require) {'use strict';
(function(exports, require) {
// Keep compatibility with old browsers // Keep compatibility with old browsers
if (!Array.isArray) { if (!Array.isArray) {
...@@ -20,9 +21,12 @@ var isNode = typeof module !== 'undefined' && !!module.exports; ...@@ -20,9 +21,12 @@ var isNode = typeof module !== 'undefined' && !!module.exports;
var vm = isNode ? var vm = isNode ?
require('vm') : { require('vm') : {
runInNewContext: function(expr, context) { with (context) return eval(expr); } runInNewContext: function(expr, context) {
return eval(Object.keys(context).reduce(function (s, vr) {
return 'var ' + vr + '=' + JSON.stringify(context[vr]) + ';' + s;
}, expr));
}
}; };
exports.eval = jsonPath;
var cache = {}; var cache = {};
...@@ -30,47 +34,51 @@ function push(arr, elem) { arr = arr.slice(); arr.push(elem); return arr; } ...@@ -30,47 +34,51 @@ function push(arr, elem) { arr = arr.slice(); arr.push(elem); return arr; }
function unshift(elem, arr) { arr = arr.slice(); arr.unshift(elem); return arr; } function unshift(elem, arr) { arr = arr.slice(); arr.unshift(elem); return arr; }
function jsonPath(obj, expr, arg) { function jsonPath(obj, expr, arg) {
var $ = obj;
var P = { var P = {
resultType: arg && arg.resultType || "VALUE", resultType: (arg && arg.resultType) || "VALUE",
flatten: arg && arg.flatten || false, flatten: (arg && arg.flatten) || false,
wrap: (arg && arg.hasOwnProperty('wrap')) ? arg.wrap : true, wrap: (arg && arg.hasOwnProperty('wrap')) ? arg.wrap : true,
sandbox: (arg && arg.sandbox) ? arg.sandbox : {}, sandbox: (arg && arg.sandbox) ? arg.sandbox : {},
normalize: function(expr) { normalize: function(expr) {
if (cache[expr]) return cache[expr]; if (cache[expr]) {return cache[expr];}
var subx = []; var subx = [];
var normalized = expr.replace(/[\['](\??\(.*?\))[\]']/g, function($0,$1){return "[#"+(subx.push($1)-1)+"]";}) var normalized = expr.replace(/[\['](\??\(.*?\))[\]']/g, function($0,$1){return "[#"+(subx.push($1)-1)+"]";})
.replace(/'?\.'?|\['?/g, ";") .replace(/'?\.'?|\['?/g, ";")
.replace(/(;)?(\^+)(;)?/g, function(_, front, ups, back) { return ';' + ups.split('').join(';') + ';'; }) .replace(/(?:;)?(\^+)(?:;)?/g, function(_, ups) { return ';' + ups.split('').join(';') + ';'; })
.replace(/;;;|;;/g, ";..;") .replace(/;;;|;;/g, ";..;")
.replace(/;$|'?\]|'$/g, ""); .replace(/;$|'?\]|'$/g, "");
var exprList = normalized.split(';').map(function(expr) { var exprList = normalized.split(';').map(function(expr) {
var match = expr.match(/#([0-9]+)/); var match = expr.match(/#([0-9]+)/);
return !match || !match[1] ? expr : subx[match[1]]; return !match || !match[1] ? expr : subx[match[1]];
}) });
return cache[expr] = exprList; cache[expr] = exprList;
return cache[expr];
}, },
asPath: function(path) { asPath: function(path) {
var x = path, p = "$"; var i, n, x = path, p = "$";
for (var i=1,n=x.length; i<n; i++) for (i=1,n=x.length; i<n; i++) {
p += /^[0-9*]+$/.test(x[i]) ? ("["+x[i]+"]") : ("['"+x[i]+"']"); p += /^[0-9*]+$/.test(x[i]) ? ("["+x[i]+"]") : ("['"+x[i]+"']");
}
return p; return p;
}, },
trace: function(expr, val, path) { trace: function(expr, val, path) {
// No expr to follow? return path and value as the result of this trace branch // No expr to follow? return path and value as the result of this trace branch
if (!expr.length) return [{path: path, value: val}]; if (!expr.length) {return [{path: path, value: val}];}
var loc = expr[0], x = expr.slice(1); var loc = expr[0], x = expr.slice(1);
// The parent sel computation is handled in the frame above using the // The parent sel computation is handled in the frame above using the
// ancestor object of val // ancestor object of val
if (loc === '^') return path.length ? [{path: path.slice(0,-1), expr: x, isParentSelector: true}] : []; if (loc === '^') {return path.length ? [{path: path.slice(0,-1), expr: x, isParentSelector: true}] : [];}
// We need to gather the return value of recursive trace calls in order to // We need to gather the return value of recursive trace calls in order to
// do the parent sel computation. // do the parent sel computation.
var ret = []; var ret = [];
function addRet(elems) { ret = ret.concat(elems); } function addRet(elems) { ret = ret.concat(elems); }
if (val && val.hasOwnProperty(loc)) // simple case, directly follow property if (val && val.hasOwnProperty(loc)) { // simple case, directly follow property
addRet(P.trace(x, val[loc], push(path, loc))); addRet(P.trace(x, val[loc], push(path, loc)));
}
else if (loc === "*") { // any property else if (loc === "*") { // any property
P.walk(loc, x, val, path, function(m,l,x,v,p) { P.walk(loc, x, val, path, function(m,l,x,v,p) {
addRet(P.trace(unshift(m, x), v, p)); }); addRet(P.trace(unshift(m, x), v, p)); });
...@@ -78,8 +86,9 @@ function jsonPath(obj, expr, arg) { ...@@ -78,8 +86,9 @@ function jsonPath(obj, expr, arg) {
else if (loc === "..") { // all child properties else if (loc === "..") { // all child properties
addRet(P.trace(x, val, path)); addRet(P.trace(x, val, path));
P.walk(loc, x, val, path, function(m,l,x,v,p) { P.walk(loc, x, val, path, function(m,l,x,v,p) {
if (typeof v[m] === "object") if (typeof v[m] === "object") {
addRet(P.trace(unshift("..", x), v[m], push(p, m))); addRet(P.trace(unshift("..", x), v[m], push(p, m)));
}
}); });
} }
else if (loc[0] === '(') { // [(expr)] else if (loc[0] === '(') { // [(expr)]
...@@ -87,13 +96,16 @@ function jsonPath(obj, expr, arg) { ...@@ -87,13 +96,16 @@ function jsonPath(obj, expr, arg) {
} }
else if (loc.indexOf('?(') === 0) { // [?(expr)] else if (loc.indexOf('?(') === 0) { // [?(expr)]
P.walk(loc, x, val, path, function(m,l,x,v,p) { P.walk(loc, x, val, path, function(m,l,x,v,p) {
if (P.eval(l.replace(/^\?\((.*?)\)$/,"$1"),v[m],m, path)) if (P.eval(l.replace(/^\?\((.*?)\)$/,"$1"),v[m],m, path)) {
addRet(P.trace(unshift(m,x),v,p)); addRet(P.trace(unshift(m,x),v,p));
}
}); });
} }
else if (loc.indexOf(',') > -1) { // [name1,name2,...] else if (loc.indexOf(',') > -1) { // [name1,name2,...]
for (var parts = loc.split(','), i = 0; i < parts.length; i++) var parts, i;
for (parts = loc.split(','), i = 0; i < parts.length; i++) {
addRet(P.trace(unshift(parts[i], x), val, path)); addRet(P.trace(unshift(parts[i], x), val, path));
}
} }
else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc)) { // [start:end:step] Python slice syntax else if (/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(loc)) { // [start:end:step] Python slice syntax
addRet(P.slice(loc, x, val, path)); addRet(P.slice(loc, x, val, path));
...@@ -107,35 +119,43 @@ function jsonPath(obj, expr, arg) { ...@@ -107,35 +119,43 @@ function jsonPath(obj, expr, arg) {
}, []); }, []);
}, },
walk: function(loc, expr, val, path, f) { walk: function(loc, expr, val, path, f) {
if (Array.isArray(val)) var i, n, m;
for (var i = 0, n = val.length; i < n; i++) if (Array.isArray(val)) {
for (i = 0, n = val.length; i < n; i++) {
f(i, loc, expr, val, path); f(i, loc, expr, val, path);
else if (typeof val === "object") }
for (var m in val) }
if (val.hasOwnProperty(m)) else if (typeof val === "object") {
for (m in val) {
if (val.hasOwnProperty(m)) {
f(m, loc, expr, val, path); f(m, loc, expr, val, path);
}
}
}
}, },
slice: function(loc, expr, val, path) { slice: function(loc, expr, val, path) {
if (!Array.isArray(val)) return; if (!Array.isArray(val)) {return;}
var len = val.length, parts = loc.split(':'), var i,
start = (parts[0] && parseInt(parts[0])) || 0, len = val.length, parts = loc.split(':'),
end = (parts[1] && parseInt(parts[1])) || len, start = (parts[0] && parseInt(parts[0], 10)) || 0,
step = (parts[2] && parseInt(parts[2])) || 1; end = (parts[1] && parseInt(parts[1], 10)) || len,
step = (parts[2] && parseInt(parts[2], 10)) || 1;
start = (start < 0) ? Math.max(0,start+len) : Math.min(len,start); start = (start < 0) ? Math.max(0,start+len) : Math.min(len,start);
end = (end < 0) ? Math.max(0,end+len) : Math.min(len,end); end = (end < 0) ? Math.max(0,end+len) : Math.min(len,end);
var ret = []; var ret = [];
for (var i = start; i < end; i += step) for (i = start; i < end; i += step) {
ret = ret.concat(P.trace(unshift(i,expr), val, path)); ret = ret.concat(P.trace(unshift(i,expr), val, path));
}
return ret; return ret;
}, },
eval: function(code, _v, _vname, path) { eval: function(code, _v, _vname, path) {
if (!$ || !_v) return false; if (!$ || !_v) {return false;}
if (code.indexOf("@path") > -1) { if (code.indexOf("@path") > -1) {
P.sandbox["_path"] = P.asPath(path.concat([_vname])); P.sandbox._path = P.asPath(path.concat([_vname]));
code = code.replace(/@path/g, "_path"); code = code.replace(/@path/g, "_path");
} }
if (code.indexOf("@") > -1) { if (code.indexOf("@") > -1) {
P.sandbox["_v"] = _v; P.sandbox._v = _v;
code = code.replace(/@/g, "_v"); code = code.replace(/@/g, "_v");
} }
try { try {
...@@ -148,18 +168,17 @@ function jsonPath(obj, expr, arg) { ...@@ -148,18 +168,17 @@ function jsonPath(obj, expr, arg) {
} }
}; };
var $ = obj;
var resultType = P.resultType.toLowerCase(); var resultType = P.resultType.toLowerCase();
if (expr && obj && (resultType == "value" || resultType == "path")) { if (expr && obj && (resultType === "value" || resultType === "path")) {
var exprList = P.normalize(expr); var exprList = P.normalize(expr);
if (exprList[0] === "$" && exprList.length > 1) exprList.shift(); if (exprList[0] === "$" && exprList.length > 1) {exprList.shift();}
var result = P.trace(exprList, obj, ["$"]); var result = P.trace(exprList, obj, ["$"]);
result = result.filter(function(ea) { return ea && !ea.isParentSelector; }); result = result.filter(function(ea) { return ea && !ea.isParentSelector; });
if (!result.length) return P.wrap ? [] : false; if (!result.length) {return P.wrap ? [] : false;}
if (result.length === 1 && !P.wrap && !Array.isArray(result[0].value)) return result[0][resultType] || false; if (result.length === 1 && !P.wrap && !Array.isArray(result[0].value)) {return result[0][resultType] || false;}
return result.reduce(function(result, ea) { return result.reduce(function(result, ea) {
var valOrPath = ea[resultType]; var valOrPath = ea[resultType];
if (resultType === 'path') valOrPath = P.asPath(valOrPath); if (resultType === 'path') {valOrPath = P.asPath(valOrPath);}
if (P.flatten && Array.isArray(valOrPath)) { if (P.flatten && Array.isArray(valOrPath)) {
result = result.concat(valOrPath); result = result.concat(valOrPath);
} else { } else {
...@@ -169,4 +188,12 @@ function jsonPath(obj, expr, arg) { ...@@ -169,4 +188,12 @@ function jsonPath(obj, expr, arg) {
}, []); }, []);
} }
} }
})(typeof exports === 'undefined' ? this['jsonPath'] = {} : exports, typeof require == "undefined" ? null : require);
if (typeof exports === 'undefined') {
window.jsonPath = {eval: jsonPath};
}
else {
exports.eval = jsonPath;
}
}(typeof require === 'undefined' ? null : require));
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment