jsonpath-plus
Version:
A JS implementation of JSONPath with some additional operators
3 lines (2 loc) • 11.8 kB
JavaScript
function _typeof(t){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&_setPrototypeOf(t,e)}function _getPrototypeOf(t){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function _setPrototypeOf(t,e){return(_setPrototypeOf=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function isNativeReflectConstruct(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}function _construct(t,e,r){return(_construct=isNativeReflectConstruct()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var a=new(Function.bind.apply(t,n));return r&&_setPrototypeOf(a,r.prototype),a}).apply(null,arguments)}function _isNativeFunction(t){return-1!==Function.toString.call(t).indexOf("[native code]")}function _wrapNativeSuper(t){var e="function"==typeof Map?new Map:void 0;return(_wrapNativeSuper=function(t){if(null===t||!_isNativeFunction(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return _construct(t,arguments,_getPrototypeOf(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(r,t)})(t)}function _assertThisInitialized(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function _possibleConstructorReturn(t,e){return!e||"object"!=typeof e&&"function"!=typeof e?_assertThisInitialized(t):e}var globalEval=eval,supportsNodeVM=!("undefined"==typeof module||!module.exports||"undefined"!=typeof navigator&&"ReactNative"===navigator.product),allowedResultTypes=["value","path","pointer","parent","parentProperty","all"],hasOwnProperty=Object.prototype.hasOwnProperty,moveToAnotherArray=function(t,e,r){for(var n=t.length,a=0;a<n;a++){r(t[a])&&e.push(t.splice(a--,1)[0])}},vm=supportsNodeVM?require("vm"):{runInNewContext:function(t,e){var r=Object.keys(e),n=[];moveToAnotherArray(r,n,function(t){return"function"==typeof e[t]});var a=n.reduce(function(t,r){var n=e[r].toString();return/function/.exec(n)||(n="function "+n),"var "+r+"="+n+";"+t},"")+r.reduce(function(t,r){return"var "+r+"="+JSON.stringify(e[r]).replace(/\u2028|\u2029/g,function(t){return"\\u202"+("\u2028"===t?"8":"9")})+";"+t},t);return globalEval(a)}};function push(t,e){return(t=t.slice()).push(e),t}function unshift(t,e){return(e=e.slice()).unshift(t),e}var NewError=function(t){function e(t){var r;return _classCallCheck(this,e),(r=_possibleConstructorReturn(this,_getPrototypeOf(e).call(this,'JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)'))).avoidNew=!0,r.value=t,r}return _inherits(e,_wrapNativeSuper(Error)),e}();function JSONPath(t,e,r,n,a){if(!(this instanceof JSONPath))try{return new JSONPath(t,e,r,n,a)}catch(t){if(!t.avoidNew)throw t;return t.value}"string"==typeof t&&(a=n,n=r,r=e,e=t,t={});var o=(t=t||{}).hasOwnProperty("json")&&t.hasOwnProperty("path");if(this.json=t.json||r,this.path=t.path||e,this.resultType=t.resultType&&t.resultType.toLowerCase()||"value",this.flatten=t.flatten||!1,this.wrap=!t.hasOwnProperty("wrap")||t.wrap,this.sandbox=t.sandbox||{},this.preventEval=t.preventEval||!1,this.parent=t.parent||null,this.parentProperty=t.parentProperty||null,this.callback=t.callback||n||null,this.otherTypeCallback=t.otherTypeCallback||a||function(){throw new Error("You must supply an otherTypeCallback callback option with the @other() operator.")},!1!==t.autostart){var i=this.evaluate({path:o?t.path:e,json:o?t.json:r});if(!i||"object"!==_typeof(i))throw new NewError(i);return i}}JSONPath.prototype.evaluate=function(t,e,r,n){var a=this,o=this.parent,i=this.parentProperty,s=this.flatten,p=this.wrap;if(this.currResultType=this.resultType,this.currPreventEval=this.preventEval,this.currSandbox=this.sandbox,r=r||this.callback,this.currOtherTypeCallback=n||this.otherTypeCallback,e=e||this.json,(t=t||this.path)&&"object"===_typeof(t)){if(!t.path)throw new Error('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');e=t.hasOwnProperty("json")?t.json:e,s=t.hasOwnProperty("flatten")?t.flatten:s,this.currResultType=t.hasOwnProperty("resultType")?t.resultType:this.currResultType,this.currSandbox=t.hasOwnProperty("sandbox")?t.sandbox:this.currSandbox,p=t.hasOwnProperty("wrap")?t.wrap:p,this.currPreventEval=t.hasOwnProperty("preventEval")?t.preventEval:this.currPreventEval,r=t.hasOwnProperty("callback")?t.callback:r,this.currOtherTypeCallback=t.hasOwnProperty("otherTypeCallback")?t.otherTypeCallback:this.currOtherTypeCallback,o=t.hasOwnProperty("parent")?t.parent:o,i=t.hasOwnProperty("parentProperty")?t.parentProperty:i,t=t.path}if(o=o||null,i=i||null,Array.isArray(t)&&(t=JSONPath.toPathString(t)),t&&e&&allowedResultTypes.includes(this.currResultType)){this._obj=e;var c=JSONPath.toPathArray(t);"$"===c[0]&&c.length>1&&c.shift(),this._hasParentSelector=null;var u=this._trace(c,e,["$"],o,i,r).filter(function(t){return t&&!t.isParentSelector});return u.length?1!==u.length||p||Array.isArray(u[0].value)?u.reduce(function(t,e){var r=a._getPreferredOutput(e);return s&&Array.isArray(r)?t=t.concat(r):t.push(r),t},[]):this._getPreferredOutput(u[0]):p?[]:void 0}},JSONPath.prototype._getPreferredOutput=function(t){var e=this.currResultType;switch(e){case"all":return t.path="string"==typeof t.path?t.path:JSONPath.toPathString(t.path),t;case"value":case"parent":case"parentProperty":return t[e];case"path":return JSONPath.toPathString(t[e]);case"pointer":return JSONPath.toPointer(t.path)}},JSONPath.prototype._handleCallback=function(t,e,r){if(e){var n=this._getPreferredOutput(t);t.path="string"==typeof t.path?t.path:JSONPath.toPathString(t.path),e(n,r,t)}},JSONPath.prototype._trace=function(t,e,r,n,a,o,i){var s,p=this;if(!t.length)return s={path:r,value:e,parent:n,parentProperty:a},this._handleCallback(s,o,"value"),s;var c=t[0],u=t.slice(1),l=[];function h(t){Array.isArray(t)?t.forEach(function(t){l.push(t)}):l.push(t)}if(("string"!=typeof c||i)&&e&&hasOwnProperty.call(e,c))h(this._trace(u,e[c],push(r,c),e,c,o));else if("*"===c)this._walk(c,u,e,r,n,a,o,function(t,e,r,n,a,o,i,s){h(p._trace(unshift(t,r),n,a,o,i,s,!0))});else if(".."===c)h(this._trace(u,e,r,n,a,o)),this._walk(c,u,e,r,n,a,o,function(t,e,r,n,a,o,i,s){"object"===_typeof(n[t])&&h(p._trace(unshift(e,r),n[t],push(a,t),n,t,s))});else{if("^"===c)return this._hasParentSelector=!0,r.length?{path:r.slice(0,-1),expr:u,isParentSelector:!0}:[];if("~"===c)return s={path:push(r,c),value:a,parent:n,parentProperty:null},this._handleCallback(s,o,"property"),s;if("$"===c)h(this._trace(u,e,r,null,null,o));else if(/^(-?[0-9]*):(-?[0-9]*):?([0-9]*)$/.test(c))h(this._slice(c,u,e,r,n,a,o));else if(0===c.indexOf("?(")){if(this.currPreventEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");this._walk(c,u,e,r,n,a,o,function(t,e,r,n,a,o,i,s){p._eval(e.replace(/^\?\((.*?)\)$/,"$1"),n[t],t,a,o,i)&&h(p._trace(unshift(t,r),n,a,o,i,s))})}else if("("===c[0]){if(this.currPreventEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");h(this._trace(unshift(this._eval(c,e,r[r.length-1],r.slice(0,-1),n,a),u),e,r,n,a,o))}else if("@"===c[0]){var f=!1,y=c.slice(1,-2);switch(y){case"scalar":e&&["object","function"].includes(_typeof(e))||(f=!0);break;case"boolean":case"string":case"undefined":case"function":_typeof(e)===y&&(f=!0);break;case"number":_typeof(e)===y&&isFinite(e)&&(f=!0);break;case"nonFinite":"number"!=typeof e||isFinite(e)||(f=!0);break;case"object":e&&_typeof(e)===y&&(f=!0);break;case"array":Array.isArray(e)&&(f=!0);break;case"other":f=this.currOtherTypeCallback(e,r,n,a);break;case"integer":e!==+e||!isFinite(e)||e%1||(f=!0);break;case"null":null===e&&(f=!0)}if(f)return s={path:r,value:e,parent:n,parentProperty:a},this._handleCallback(s,o,"value"),s}else if("`"===c[0]&&e&&hasOwnProperty.call(e,c.slice(1))){var v=c.slice(1);h(this._trace(u,e[v],push(r,v),e,v,o,!0))}else if(c.includes(",")){var P=c.split(","),_=!0,b=!1,O=void 0;try{for(var w,g=P[Symbol.iterator]();!(_=(w=g.next()).done);_=!0){var d=w.value;h(this._trace(unshift(d,u),e,r,n,a,o))}}catch(t){b=!0,O=t}finally{try{_||null==g.return||g.return()}finally{if(b)throw O}}}else!i&&e&&hasOwnProperty.call(e,c)&&h(this._trace(u,e[c],push(r,c),e,c,o,!0))}if(this._hasParentSelector)for(var S=0;S<l.length;S++){var N=l[S];if(N.isParentSelector){var k=p._trace(N.expr,e,N.path,n,a,o);if(Array.isArray(k)){l[S]=k[0];for(var m=k.length,x=1;x<m;x++)S++,l.splice(S,0,k[x])}else l[S]=k}}return l},JSONPath.prototype._walk=function(t,e,r,n,a,o,i,s){if(Array.isArray(r))for(var p=r.length,c=0;c<p;c++)s(c,t,e,r,n,a,o,i);else if("object"===_typeof(r))for(var u in r)hasOwnProperty.call(r,u)&&s(u,t,e,r,n,a,o,i)},JSONPath.prototype._slice=function(t,e,r,n,a,o,i){if(Array.isArray(r)){var s=r.length,p=t.split(":"),c=p[2]&&parseInt(p[2],10)||1,u=p[0]&&parseInt(p[0],10)||0,l=p[1]&&parseInt(p[1],10)||s;u=u<0?Math.max(0,u+s):Math.min(s,u),l=l<0?Math.max(0,l+s):Math.min(s,l);for(var h=[],f=u;f<l;f+=c){var y=this._trace(unshift(f,e),r,n,a,o,i);Array.isArray(y)?y.forEach(function(t){h.push(t)}):h.push(y)}return h}},JSONPath.prototype._eval=function(t,e,r,n,a,o){if(!this._obj||!e)return!1;t.includes("@parentProperty")&&(this.currSandbox._$_parentProperty=o,t=t.replace(//g,"_$_parentProperty")),t.includes("@parent")&&(this.currSandbox._$_parent=a,t=t.replace(//g,"_$_parent")),t.includes("@property")&&(this.currSandbox._$_property=r,t=t.replace(//g,"_$_property")),t.includes("@path")&&(this.currSandbox._$_path=JSONPath.toPathString(n.concat([r])),t=t.replace(//g,"_$_path")),t.match(/@([.\s)[])/)&&(this.currSandbox._$_v=e,t=t.replace(/@([.\s)[])/g,"_$_v$1"));try{return vm.runInNewContext(t,this.currSandbox)}catch(e){throw console.log(e),new Error("jsonPath: "+e.message+": "+t)}},JSONPath.cache={},JSONPath.toPathString=function(t){for(var e=t,r=e.length,n="$",a=1;a<r;a++)/^(~|\^|@.*?\(\))$/.test(e[a])||(n+=/^[0-9*]+$/.test(e[a])?"["+e[a]+"]":"['"+e[a]+"']");return n},JSONPath.toPointer=function(t){for(var e=t,r=e.length,n="",a=1;a<r;a++)/^(~|\^|@.*?\(\))$/.test(e[a])||(n+="/"+e[a].toString().replace(/~/g,"~0").replace(/\//g,"~1"));return n},JSONPath.toPathArray=function(t){var e=JSONPath.cache;if(e[t])return e[t].concat();var r=[],n=t.replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g,";$&;").replace(/[['](\??\(.*?\))[\]']/g,function(t,e){return"[#"+(r.push(e)-1)+"]"}).replace(/\['([^'\]]*)'\]/g,function(t,e){return"['"+e.replace(/\./g,"%@%").replace(/~/g,"%%@@%%")+"']"}).replace(/~/g,";~;").replace(/'?\.'?(?![^[]*\])|\['?/g,";").replace(/%@%/g,".").replace(/%%@@%%/g,"~").replace(/(?:;)?(\^+)(?:;)?/g,function(t,e){return";"+e.split("").join(";")+";"}).replace(/;;;|;;/g,";..;").replace(/;$|'?\]|'$/g,"").split(";").map(function(t){var e=t.match(/#([0-9]+)/);return e&&e[1]?r[e[1]]:t});return e[t]=n,e[t]};export{JSONPath};
//# sourceMappingURL=index-es.min.js.map