Socket
Socket
Sign inDemoInstall

jsonpath-plus

Package Overview
Dependencies
Maintainers
1
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jsonpath-plus - npm Package Compare versions

Comparing version 7.1.0 to 7.2.0

9

CHANGES.md
# CHANGES for jsonpath-plus
## 7.2.0
- perf: optimize walk method by 10%-34% (@jacobroschen)
- chore: add types to exports field (@awlayton)
## 7.1.0
- perf: improve evaluation speed of conditional queries (@jacobroschen)
## 7.0.0

@@ -4,0 +13,0 @@

24

dist/index-browser-esm.js

@@ -638,4 +638,4 @@ function _typeof(obj) {

// all child properties
this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, _x, v, p, par, pr, cb) {
addRet(_this3._trace(unshift(m, _x), v, p, par, pr, cb, true, true));
this._walk(val, function (m) {
addRet(_this3._trace(x, val[m], push(path, m), val, m, callback, true, true));
});

@@ -647,9 +647,9 @@ } else if (loc === '..') {

this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, _x, v, p, par, pr, cb) {
this._walk(val, function (m) {
// We don't join m and x here because we only want parents,
// not scalar values
if (_typeof(v[m]) === 'object') {
if (_typeof(val[m]) === 'object') {
// Keep going with recursive descent on val's
// object children
addRet(_this3._trace(unshift(l, _x), v[m], push(p, m), v, m, cb, true));
addRet(_this3._trace(expr.slice(), val[m], push(path, m), val, m, callback, true));
}

@@ -691,5 +691,7 @@ }); // The parent sel computation is handled in the frame above using the

this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, _x, v, p, par, pr, cb) {
if (_this3._eval(l.replace(/^\?\(((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?)\)$/, '$1'), v[m], m, p, par, pr)) {
addRet(_this3._trace(unshift(m, _x), v, p, par, pr, cb, true));
var safeLoc = loc.replace(/^\?\(((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?)\)$/, '$1');
this._walk(val, function (m) {
if (_this3._eval(safeLoc, val[m], m, path, parent, parentPropName)) {
addRet(_this3._trace(x, val[m], push(path, m), val, m, callback, true));
}

@@ -850,3 +852,3 @@ });

JSONPath.prototype._walk = function (loc, expr, val, path, parent, parentPropName, callback, f) {
JSONPath.prototype._walk = function (val, f) {
if (Array.isArray(val)) {

@@ -856,7 +858,7 @@ var n = val.length;

for (var i = 0; i < n; i++) {
f(i, loc, expr, val, path, parent, parentPropName, callback);
f(i);
}
} else if (val && _typeof(val) === 'object') {
Object.keys(val).forEach(function (m) {
f(m, loc, expr, val, path, parent, parentPropName, callback);
f(m);
});

@@ -863,0 +865,0 @@ }

@@ -1,2 +0,2 @@

function t(r){return t="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(r)}function r(t,r){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")}function e(t,r){for(var e=0;e<r.length;e++){var n=r[e];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function n(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function a(t){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},a(t)}function o(t,r){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,r){return t.__proto__=r,t},o(t,r)}function u(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function i(t,r,e){return i=u()?Reflect.construct.bind():function(t,r,e){var n=[null];n.push.apply(n,r);var a=new(Function.bind.apply(t,n));return e&&o(a,e.prototype),a},i.apply(null,arguments)}function c(t){var r="function"==typeof Map?new Map:void 0;return c=function(t){if(null===t||(e=t,-1===Function.toString.call(e).indexOf("[native code]")))return t;var e;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,n)}function n(){return i(t,arguments,a(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),o(n,t)},c(t)}function l(t,r){if(r&&("object"==typeof r||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function s(t){return function(t){if(Array.isArray(t))return h(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||p(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(t,r){if(t){if("string"==typeof t)return h(t,r);var e=Object.prototype.toString.call(t).slice(8,-1);return"Object"===e&&t.constructor&&(e=t.constructor.name),"Map"===e||"Set"===e?Array.from(t):"Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?h(t,r):void 0}}function h(t,r){(null==r||r>t.length)&&(r=t.length);for(var e=0,n=new Array(r);e<r;e++)n[e]=t[e];return n}var f=Object.prototype.hasOwnProperty;function y(t,r){return(t=t.slice()).push(r),t}function v(t,r){return(r=r.slice()).unshift(t),r}var b=function(t){!function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(r&&r.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),r&&o(t,r)}(p,c(Error));var e,i,s=(e=p,i=u(),function(){var t,r=a(e);if(i){var n=a(this).constructor;t=Reflect.construct(r,arguments,n)}else t=r.apply(this,arguments);return l(this,t)});function p(t){var e;return r(this,p),(e=s.call(this,'JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)')).avoidNew=!0,e.value=t,e.name="NewError",e}return n(p)}();function F(r,e,n,a,o){if(!(this instanceof F))try{return new F(r,e,n,a,o)}catch(t){if(!t.avoidNew)throw t;return t.value}"string"==typeof r&&(o=a,a=n,n=e,e=r,r=null);var u=r&&"object"===t(r);if(r=r||{},this.json=r.json||n,this.path=r.path||e,this.resultType=r.resultType||"value",this.flatten=r.flatten||!1,this.wrap=!f.call(r,"wrap")||r.wrap,this.sandbox=r.sandbox||{},this.preventEval=r.preventEval||!1,this.parent=r.parent||null,this.parentProperty=r.parentProperty||null,this.callback=r.callback||a||null,this.otherTypeCallback=r.otherTypeCallback||o||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},!1!==r.autostart){var i={path:u?r.path:e};u?"json"in r&&(i.json=r.json):i.json=n;var c=this.evaluate(i);if(!c||"object"!==t(c))throw new b(c);return c}}F.prototype.evaluate=function(r,e,n,a){var o=this,u=this.parent,i=this.parentProperty,c=this.flatten,l=this.wrap;if(this.currResultType=this.resultType,this.currPreventEval=this.preventEval,this.currSandbox=this.sandbox,n=n||this.callback,this.currOtherTypeCallback=a||this.otherTypeCallback,e=e||this.json,(r=r||this.path)&&"object"===t(r)&&!Array.isArray(r)){if(!r.path&&""!==r.path)throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!f.call(r,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');e=r.json,c=f.call(r,"flatten")?r.flatten:c,this.currResultType=f.call(r,"resultType")?r.resultType:this.currResultType,this.currSandbox=f.call(r,"sandbox")?r.sandbox:this.currSandbox,l=f.call(r,"wrap")?r.wrap:l,this.currPreventEval=f.call(r,"preventEval")?r.preventEval:this.currPreventEval,n=f.call(r,"callback")?r.callback:n,this.currOtherTypeCallback=f.call(r,"otherTypeCallback")?r.otherTypeCallback:this.currOtherTypeCallback,u=f.call(r,"parent")?r.parent:u,i=f.call(r,"parentProperty")?r.parentProperty:i,r=r.path}if(u=u||null,i=i||null,Array.isArray(r)&&(r=F.toPathString(r)),(r||""===r)&&e){var s=F.toPathArray(r);"$"===s[0]&&s.length>1&&s.shift(),this._hasParentSelector=null;var p=this._trace(s,e,["$"],u,i,n).filter((function(t){return t&&!t.isParentSelector}));return p.length?l||1!==p.length||p[0].hasArrExpr?p.reduce((function(t,r){var e=o._getPreferredOutput(r);return c&&Array.isArray(e)?t=t.concat(e):t.push(e),t}),[]):this._getPreferredOutput(p[0]):l?[]:void 0}},F.prototype._getPreferredOutput=function(t){var r=this.currResultType;switch(r){case"all":var e=Array.isArray(t.path)?t.path:F.toPathArray(t.path);return t.pointer=F.toPointer(e),t.path="string"==typeof t.path?t.path:F.toPathString(t.path),t;case"value":case"parent":case"parentProperty":return t[r];case"path":return F.toPathString(t[r]);case"pointer":return F.toPointer(t.path);default:throw new TypeError("Unknown result type")}},F.prototype._handleCallback=function(t,r,e){if(r){var n=this._getPreferredOutput(t);t.path="string"==typeof t.path?t.path:F.toPathString(t.path),r(n,e,t)}},F.prototype._trace=function(r,e,n,a,o,u,i,c){var l,s=this;if(!r.length)return l={path:n,value:e,parent:a,parentProperty:o,hasArrExpr:i},this._handleCallback(l,u,"value"),l;var h=r[0],b=r.slice(1),F=[];function d(t){Array.isArray(t)?t.forEach((function(t){F.push(t)})):F.push(t)}if(("string"!=typeof h||c)&&e&&f.call(e,h))d(this._trace(b,e[h],y(n,h),e,h,u,i));else if("*"===h)this._walk(h,b,e,n,a,o,u,(function(t,r,e,n,a,o,u,i){d(s._trace(v(t,e),n,a,o,u,i,!0,!0))}));else if(".."===h)d(this._trace(b,e,n,a,o,u,i)),this._walk(h,b,e,n,a,o,u,(function(r,e,n,a,o,u,i,c){"object"===t(a[r])&&d(s._trace(v(e,n),a[r],y(o,r),a,r,c,!0))}));else{if("^"===h)return this._hasParentSelector=!0,{path:n.slice(0,-1),expr:b,isParentSelector:!0};if("~"===h)return l={path:y(n,h),value:o,parent:a,parentProperty:null},this._handleCallback(l,u,"property"),l;if("$"===h)d(this._trace(b,e,n,null,null,u,i));else if(/^(\x2D?[0-9]*):(\x2D?[0-9]*):?([0-9]*)$/.test(h))d(this._slice(h,b,e,n,a,o,u));else if(0===h.indexOf("?(")){if(this.currPreventEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");this._walk(h,b,e,n,a,o,u,(function(t,r,e,n,a,o,u,i){s._eval(r.replace(/^\?\(((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?)\)$/,"$1"),n[t],t,a,o,u)&&d(s._trace(v(t,e),n,a,o,u,i,!0))}))}else if("("===h[0]){if(this.currPreventEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");d(this._trace(v(this._eval(h,e,n[n.length-1],n.slice(0,-1),a,o),b),e,n,a,o,u,i))}else if("@"===h[0]){var g=!1,w=h.slice(1,-2);switch(w){case"scalar":e&&["object","function"].includes(t(e))||(g=!0);break;case"boolean":case"string":case"undefined":case"function":t(e)===w&&(g=!0);break;case"integer":!Number.isFinite(e)||e%1||(g=!0);break;case"number":Number.isFinite(e)&&(g=!0);break;case"nonFinite":"number"!=typeof e||Number.isFinite(e)||(g=!0);break;case"object":e&&t(e)===w&&(g=!0);break;case"array":Array.isArray(e)&&(g=!0);break;case"other":g=this.currOtherTypeCallback(e,n,a,o);break;case"null":null===e&&(g=!0);break;default:throw new TypeError("Unknown value type "+w)}if(g)return l={path:n,value:e,parent:a,parentProperty:o},this._handleCallback(l,u,"value"),l}else if("`"===h[0]&&e&&f.call(e,h.slice(1))){var _=h.slice(1);d(this._trace(b,e[_],y(n,_),e,_,u,i,!0))}else if(h.includes(",")){var m,D=function(t,r){var e="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!e){if(Array.isArray(t)||(e=p(t))||r&&t&&"number"==typeof t.length){e&&(t=e);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,u=!0,i=!1;return{s:function(){e=e.call(t)},n:function(){var t=e.next();return u=t.done,t},e:function(t){i=!0,o=t},f:function(){try{u||null==e.return||e.return()}finally{if(i)throw o}}}}(h.split(","));try{for(D.s();!(m=D.n()).done;){var P=m.value;d(this._trace(v(P,b),e,n,a,o,u,!0))}}catch(t){D.e(t)}finally{D.f()}}else!c&&e&&f.call(e,h)&&d(this._trace(b,e[h],y(n,h),e,h,u,i,!0))}if(this._hasParentSelector)for(var S=0;S<F.length;S++){var x=F[S];if(x&&x.isParentSelector){var E=this._trace(x.expr,e,x.path,a,o,u,i);if(Array.isArray(E)){F[S]=E[0];for(var j=E.length,A=1;A<j;A++)S++,F.splice(S,0,E[A])}else F[S]=E}}return F},F.prototype._walk=function(r,e,n,a,o,u,i,c){if(Array.isArray(n))for(var l=n.length,s=0;s<l;s++)c(s,r,e,n,a,o,u,i);else n&&"object"===t(n)&&Object.keys(n).forEach((function(t){c(t,r,e,n,a,o,u,i)}))},F.prototype._slice=function(t,r,e,n,a,o,u){if(Array.isArray(e)){var i=e.length,c=t.split(":"),l=c[2]&&Number.parseInt(c[2])||1,s=c[0]&&Number.parseInt(c[0])||0,p=c[1]&&Number.parseInt(c[1])||i;s=s<0?Math.max(0,s+i):Math.min(i,s),p=p<0?Math.max(0,p+i):Math.min(i,p);for(var h=[],f=s;f<p;f+=l){this._trace(v(f,r),e,n,a,o,u,!0).forEach((function(t){h.push(t)}))}return h}},F.prototype._eval=function(t,r,e,n,a,o){this.currSandbox._$_parentProperty=o,this.currSandbox._$_parent=a,this.currSandbox._$_property=e,this.currSandbox._$_root=this.json,this.currSandbox._$_v=r;var u=t.includes("@path");u&&(this.currSandbox._$_path=F.toPathString(n.concat([e])));var i="script:"+t;if(!F.cache[i]){var c=t.replace(/@parentProperty/g,"_$_parentProperty").replace(/@parent/g,"_$_parent").replace(/@property/g,"_$_property").replace(/@root/g,"_$_root").replace(/@([\t-\r \)\.\[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF])/g,"_$_v$1");u&&(c=c.replace(/@path/g,"_$_path")),F.cache[i]=new this.vm.Script(c)}try{return F.cache[i].runInNewContext(this.currSandbox)}catch(r){throw new Error("jsonPath: "+r.message+": "+t)}},F.cache={},F.toPathString=function(t){for(var r=t,e=r.length,n="$",a=1;a<e;a++)/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(r[a])||(n+=/^[\*0-9]+$/.test(r[a])?"["+r[a]+"]":"['"+r[a]+"']");return n},F.toPointer=function(t){for(var r=t,e=r.length,n="",a=1;a<e;a++)/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(r[a])||(n+="/"+r[a].toString().replace(/~/g,"~0").replace(/\//g,"~1"));return n},F.toPathArray=function(t){var r=F.cache;if(r[t])return r[t].concat();var e=[],n=t.replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g,";$&;").replace(/['\[](\??\((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\))['\]]/g,(function(t,r){return"[#"+(e.push(r)-1)+"]"})).replace(/\[["']((?:(?!['\]])[\s\S])*)["']\]/g,(function(t,r){return"['"+r.replace(/\./g,"%@%").replace(/~/g,"%%@@%%")+"']"})).replace(/~/g,";~;").replace(/["']?\.["']?(?!(?:(?!\[)[\s\S])*\])|\[["']?/g,";").replace(/%@%/g,".").replace(/%%@@%%/g,"~").replace(/(?:;)?(\^+)(?:;)?/g,(function(t,r){return";"+r.split("").join(";")+";"})).replace(/;;;|;;/g,";..;").replace(/;$|'?\]|'$/g,"").split(";").map((function(t){var r=t.match(/#([0-9]+)/);return r&&r[1]?e[r[1]]:t}));return r[t]=n,r[t].concat()};var d=function(){function t(e){r(this,t),this.code=e}return n(t,[{key:"runInNewContext",value:function(t){var r=this.code,e=Object.keys(t),n=[];!function(t,r,e){for(var n=t.length,a=0;a<n;a++)e(t[a])&&r.push(t.splice(a--,1)[0])}(e,n,(function(r){return"function"==typeof t[r]}));var a=e.map((function(r,e){return t[r]})),o=n.reduce((function(r,e){var n=t[e].toString();return/function/.test(n)||(n="function "+n),"var "+e+"="+n+";"+r}),"");/(["'])use strict\1/.test(r=o+r)||e.includes("arguments")||(r="var arguments = undefined;"+r);var u=(r=r.replace(/;[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*$/,"")).lastIndexOf(";"),c=u>-1?r.slice(0,u+1)+" return "+r.slice(u+1):" return "+r;return i(Function,e.concat([c])).apply(void 0,s(a))}}]),t}();F.prototype.vm={Script:d};export{F as JSONPath};
function t(r){return t="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(r)}function r(t,r){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")}function e(t,r){for(var e=0;e<r.length;e++){var n=r[e];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function n(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t}function a(t){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},a(t)}function o(t,r){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,r){return t.__proto__=r,t},o(t,r)}function u(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function i(t,r,e){return i=u()?Reflect.construct.bind():function(t,r,e){var n=[null];n.push.apply(n,r);var a=new(Function.bind.apply(t,n));return e&&o(a,e.prototype),a},i.apply(null,arguments)}function c(t){var r="function"==typeof Map?new Map:void 0;return c=function(t){if(null===t||(e=t,-1===Function.toString.call(e).indexOf("[native code]")))return t;var e;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(t))return r.get(t);r.set(t,n)}function n(){return i(t,arguments,a(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),o(n,t)},c(t)}function l(t,r){if(r&&("object"==typeof r||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function s(t){return function(t){if(Array.isArray(t))return h(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||p(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function p(t,r){if(t){if("string"==typeof t)return h(t,r);var e=Object.prototype.toString.call(t).slice(8,-1);return"Object"===e&&t.constructor&&(e=t.constructor.name),"Map"===e||"Set"===e?Array.from(t):"Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?h(t,r):void 0}}function h(t,r){(null==r||r>t.length)&&(r=t.length);for(var e=0,n=new Array(r);e<r;e++)n[e]=t[e];return n}var f=Object.prototype.hasOwnProperty;function y(t,r){return(t=t.slice()).push(r),t}function v(t,r){return(r=r.slice()).unshift(t),r}var b=function(t){!function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(r&&r.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),r&&o(t,r)}(p,c(Error));var e,i,s=(e=p,i=u(),function(){var t,r=a(e);if(i){var n=a(this).constructor;t=Reflect.construct(r,arguments,n)}else t=r.apply(this,arguments);return l(this,t)});function p(t){var e;return r(this,p),(e=s.call(this,'JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)')).avoidNew=!0,e.value=t,e.name="NewError",e}return n(p)}();function F(r,e,n,a,o){if(!(this instanceof F))try{return new F(r,e,n,a,o)}catch(t){if(!t.avoidNew)throw t;return t.value}"string"==typeof r&&(o=a,a=n,n=e,e=r,r=null);var u=r&&"object"===t(r);if(r=r||{},this.json=r.json||n,this.path=r.path||e,this.resultType=r.resultType||"value",this.flatten=r.flatten||!1,this.wrap=!f.call(r,"wrap")||r.wrap,this.sandbox=r.sandbox||{},this.preventEval=r.preventEval||!1,this.parent=r.parent||null,this.parentProperty=r.parentProperty||null,this.callback=r.callback||a||null,this.otherTypeCallback=r.otherTypeCallback||o||function(){throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.")},!1!==r.autostart){var i={path:u?r.path:e};u?"json"in r&&(i.json=r.json):i.json=n;var c=this.evaluate(i);if(!c||"object"!==t(c))throw new b(c);return c}}F.prototype.evaluate=function(r,e,n,a){var o=this,u=this.parent,i=this.parentProperty,c=this.flatten,l=this.wrap;if(this.currResultType=this.resultType,this.currPreventEval=this.preventEval,this.currSandbox=this.sandbox,n=n||this.callback,this.currOtherTypeCallback=a||this.otherTypeCallback,e=e||this.json,(r=r||this.path)&&"object"===t(r)&&!Array.isArray(r)){if(!r.path&&""!==r.path)throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');if(!f.call(r,"json"))throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');e=r.json,c=f.call(r,"flatten")?r.flatten:c,this.currResultType=f.call(r,"resultType")?r.resultType:this.currResultType,this.currSandbox=f.call(r,"sandbox")?r.sandbox:this.currSandbox,l=f.call(r,"wrap")?r.wrap:l,this.currPreventEval=f.call(r,"preventEval")?r.preventEval:this.currPreventEval,n=f.call(r,"callback")?r.callback:n,this.currOtherTypeCallback=f.call(r,"otherTypeCallback")?r.otherTypeCallback:this.currOtherTypeCallback,u=f.call(r,"parent")?r.parent:u,i=f.call(r,"parentProperty")?r.parentProperty:i,r=r.path}if(u=u||null,i=i||null,Array.isArray(r)&&(r=F.toPathString(r)),(r||""===r)&&e){var s=F.toPathArray(r);"$"===s[0]&&s.length>1&&s.shift(),this._hasParentSelector=null;var p=this._trace(s,e,["$"],u,i,n).filter((function(t){return t&&!t.isParentSelector}));return p.length?l||1!==p.length||p[0].hasArrExpr?p.reduce((function(t,r){var e=o._getPreferredOutput(r);return c&&Array.isArray(e)?t=t.concat(e):t.push(e),t}),[]):this._getPreferredOutput(p[0]):l?[]:void 0}},F.prototype._getPreferredOutput=function(t){var r=this.currResultType;switch(r){case"all":var e=Array.isArray(t.path)?t.path:F.toPathArray(t.path);return t.pointer=F.toPointer(e),t.path="string"==typeof t.path?t.path:F.toPathString(t.path),t;case"value":case"parent":case"parentProperty":return t[r];case"path":return F.toPathString(t[r]);case"pointer":return F.toPointer(t.path);default:throw new TypeError("Unknown result type")}},F.prototype._handleCallback=function(t,r,e){if(r){var n=this._getPreferredOutput(t);t.path="string"==typeof t.path?t.path:F.toPathString(t.path),r(n,e,t)}},F.prototype._trace=function(r,e,n,a,o,u,i,c){var l,s=this;if(!r.length)return l={path:n,value:e,parent:a,parentProperty:o,hasArrExpr:i},this._handleCallback(l,u,"value"),l;var h=r[0],b=r.slice(1),F=[];function d(t){Array.isArray(t)?t.forEach((function(t){F.push(t)})):F.push(t)}if(("string"!=typeof h||c)&&e&&f.call(e,h))d(this._trace(b,e[h],y(n,h),e,h,u,i));else if("*"===h)this._walk(e,(function(t){d(s._trace(b,e[t],y(n,t),e,t,u,!0,!0))}));else if(".."===h)d(this._trace(b,e,n,a,o,u,i)),this._walk(e,(function(a){"object"===t(e[a])&&d(s._trace(r.slice(),e[a],y(n,a),e,a,u,!0))}));else{if("^"===h)return this._hasParentSelector=!0,{path:n.slice(0,-1),expr:b,isParentSelector:!0};if("~"===h)return l={path:y(n,h),value:o,parent:a,parentProperty:null},this._handleCallback(l,u,"property"),l;if("$"===h)d(this._trace(b,e,n,null,null,u,i));else if(/^(\x2D?[0-9]*):(\x2D?[0-9]*):?([0-9]*)$/.test(h))d(this._slice(h,b,e,n,a,o,u));else if(0===h.indexOf("?(")){if(this.currPreventEval)throw new Error("Eval [?(expr)] prevented in JSONPath expression.");var g=h.replace(/^\?\(((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?)\)$/,"$1");this._walk(e,(function(t){s._eval(g,e[t],t,n,a,o)&&d(s._trace(b,e[t],y(n,t),e,t,u,!0))}))}else if("("===h[0]){if(this.currPreventEval)throw new Error("Eval [(expr)] prevented in JSONPath expression.");d(this._trace(v(this._eval(h,e,n[n.length-1],n.slice(0,-1),a,o),b),e,n,a,o,u,i))}else if("@"===h[0]){var w=!1,_=h.slice(1,-2);switch(_){case"scalar":e&&["object","function"].includes(t(e))||(w=!0);break;case"boolean":case"string":case"undefined":case"function":t(e)===_&&(w=!0);break;case"integer":!Number.isFinite(e)||e%1||(w=!0);break;case"number":Number.isFinite(e)&&(w=!0);break;case"nonFinite":"number"!=typeof e||Number.isFinite(e)||(w=!0);break;case"object":e&&t(e)===_&&(w=!0);break;case"array":Array.isArray(e)&&(w=!0);break;case"other":w=this.currOtherTypeCallback(e,n,a,o);break;case"null":null===e&&(w=!0);break;default:throw new TypeError("Unknown value type "+_)}if(w)return l={path:n,value:e,parent:a,parentProperty:o},this._handleCallback(l,u,"value"),l}else if("`"===h[0]&&e&&f.call(e,h.slice(1))){var m=h.slice(1);d(this._trace(b,e[m],y(n,m),e,m,u,i,!0))}else if(h.includes(",")){var D,P=function(t,r){var e="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!e){if(Array.isArray(t)||(e=p(t))||r&&t&&"number"==typeof t.length){e&&(t=e);var n=0,a=function(){};return{s:a,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:a}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,u=!0,i=!1;return{s:function(){e=e.call(t)},n:function(){var t=e.next();return u=t.done,t},e:function(t){i=!0,o=t},f:function(){try{u||null==e.return||e.return()}finally{if(i)throw o}}}}(h.split(","));try{for(P.s();!(D=P.n()).done;){var S=D.value;d(this._trace(v(S,b),e,n,a,o,u,!0))}}catch(t){P.e(t)}finally{P.f()}}else!c&&e&&f.call(e,h)&&d(this._trace(b,e[h],y(n,h),e,h,u,i,!0))}if(this._hasParentSelector)for(var x=0;x<F.length;x++){var E=F[x];if(E&&E.isParentSelector){var j=this._trace(E.expr,e,E.path,a,o,u,i);if(Array.isArray(j)){F[x]=j[0];for(var A=j.length,k=1;k<A;k++)x++,F.splice(x,0,j[k])}else F[x]=j}}return F},F.prototype._walk=function(r,e){if(Array.isArray(r))for(var n=r.length,a=0;a<n;a++)e(a);else r&&"object"===t(r)&&Object.keys(r).forEach((function(t){e(t)}))},F.prototype._slice=function(t,r,e,n,a,o,u){if(Array.isArray(e)){var i=e.length,c=t.split(":"),l=c[2]&&Number.parseInt(c[2])||1,s=c[0]&&Number.parseInt(c[0])||0,p=c[1]&&Number.parseInt(c[1])||i;s=s<0?Math.max(0,s+i):Math.min(i,s),p=p<0?Math.max(0,p+i):Math.min(i,p);for(var h=[],f=s;f<p;f+=l){this._trace(v(f,r),e,n,a,o,u,!0).forEach((function(t){h.push(t)}))}return h}},F.prototype._eval=function(t,r,e,n,a,o){this.currSandbox._$_parentProperty=o,this.currSandbox._$_parent=a,this.currSandbox._$_property=e,this.currSandbox._$_root=this.json,this.currSandbox._$_v=r;var u=t.includes("@path");u&&(this.currSandbox._$_path=F.toPathString(n.concat([e])));var i="script:"+t;if(!F.cache[i]){var c=t.replace(/@parentProperty/g,"_$_parentProperty").replace(/@parent/g,"_$_parent").replace(/@property/g,"_$_property").replace(/@root/g,"_$_root").replace(/@([\t-\r \)\.\[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF])/g,"_$_v$1");u&&(c=c.replace(/@path/g,"_$_path")),F.cache[i]=new this.vm.Script(c)}try{return F.cache[i].runInNewContext(this.currSandbox)}catch(r){throw new Error("jsonPath: "+r.message+": "+t)}},F.cache={},F.toPathString=function(t){for(var r=t,e=r.length,n="$",a=1;a<e;a++)/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(r[a])||(n+=/^[\*0-9]+$/.test(r[a])?"["+r[a]+"]":"['"+r[a]+"']");return n},F.toPointer=function(t){for(var r=t,e=r.length,n="",a=1;a<e;a++)/^(~|\^|@(?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\(\))$/.test(r[a])||(n+="/"+r[a].toString().replace(/~/g,"~0").replace(/\//g,"~1"));return n},F.toPathArray=function(t){var r=F.cache;if(r[t])return r[t].concat();var e=[],n=t.replace(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/g,";$&;").replace(/['\[](\??\((?:[\0-\t\x0B\f\x0E-\u2027\u202A-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*?\))['\]]/g,(function(t,r){return"[#"+(e.push(r)-1)+"]"})).replace(/\[["']((?:(?!['\]])[\s\S])*)["']\]/g,(function(t,r){return"['"+r.replace(/\./g,"%@%").replace(/~/g,"%%@@%%")+"']"})).replace(/~/g,";~;").replace(/["']?\.["']?(?!(?:(?!\[)[\s\S])*\])|\[["']?/g,";").replace(/%@%/g,".").replace(/%%@@%%/g,"~").replace(/(?:;)?(\^+)(?:;)?/g,(function(t,r){return";"+r.split("").join(";")+";"})).replace(/;;;|;;/g,";..;").replace(/;$|'?\]|'$/g,"").split(";").map((function(t){var r=t.match(/#([0-9]+)/);return r&&r[1]?e[r[1]]:t}));return r[t]=n,r[t].concat()};var d=function(){function t(e){r(this,t),this.code=e}return n(t,[{key:"runInNewContext",value:function(t){var r=this.code,e=Object.keys(t),n=[];!function(t,r,e){for(var n=t.length,a=0;a<n;a++)e(t[a])&&r.push(t.splice(a--,1)[0])}(e,n,(function(r){return"function"==typeof t[r]}));var a=e.map((function(r,e){return t[r]})),o=n.reduce((function(r,e){var n=t[e].toString();return/function/.test(n)||(n="function "+n),"var "+e+"="+n+";"+r}),"");/(["'])use strict\1/.test(r=o+r)||e.includes("arguments")||(r="var arguments = undefined;"+r);var u=(r=r.replace(/;[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*$/,"")).lastIndexOf(";"),c=u>-1?r.slice(0,u+1)+" return "+r.slice(u+1):" return "+r;return i(Function,e.concat([c])).apply(void 0,s(a))}}]),t}();F.prototype.vm={Script:d};export{F as JSONPath};
//# sourceMappingURL=index-browser-esm.min.js.map

@@ -368,4 +368,4 @@ import vm from 'vm';

// all child properties
this._walk(loc, x, val, path, parent, parentPropName, callback, (m, l, _x, v, p, par, pr, cb) => {
addRet(this._trace(unshift(m, _x), v, p, par, pr, cb, true, true));
this._walk(val, m => {
addRet(this._trace(x, val[m], push(path, m), val, m, callback, true, true));
});

@@ -377,9 +377,9 @@ } else if (loc === '..') {

this._walk(loc, x, val, path, parent, parentPropName, callback, (m, l, _x, v, p, par, pr, cb) => {
this._walk(val, m => {
// We don't join m and x here because we only want parents,
// not scalar values
if (typeof v[m] === 'object') {
if (typeof val[m] === 'object') {
// Keep going with recursive descent on val's
// object children
addRet(this._trace(unshift(l, _x), v[m], push(p, m), v, m, cb, true));
addRet(this._trace(expr.slice(), val[m], push(path, m), val, m, callback, true));
}

@@ -421,5 +421,7 @@ }); // The parent sel computation is handled in the frame above using the

this._walk(loc, x, val, path, parent, parentPropName, callback, (m, l, _x, v, p, par, pr, cb) => {
if (this._eval(l.replace(/^\?\((.*?)\)$/u, '$1'), v[m], m, p, par, pr)) {
addRet(this._trace(unshift(m, _x), v, p, par, pr, cb, true));
const safeLoc = loc.replace(/^\?\((.*?)\)$/u, '$1');
this._walk(val, m => {
if (this._eval(safeLoc, val[m], m, path, parent, parentPropName)) {
addRet(this._trace(x, val[m], push(path, m), val, m, callback, true));
}

@@ -570,3 +572,3 @@ });

JSONPath.prototype._walk = function (loc, expr, val, path, parent, parentPropName, callback, f) {
JSONPath.prototype._walk = function (val, f) {
if (Array.isArray(val)) {

@@ -576,7 +578,7 @@ const n = val.length;

for (let i = 0; i < n; i++) {
f(i, loc, expr, val, path, parent, parentPropName, callback);
f(i);
}
} else if (val && typeof val === 'object') {
Object.keys(val).forEach(m => {
f(m, loc, expr, val, path, parent, parentPropName, callback);
f(m);
});

@@ -583,0 +585,0 @@ }

{
"author": "Stefan Goessner",
"name": "jsonpath-plus",
"version": "7.1.0",
"version": "7.2.0",
"type": "module",

@@ -10,2 +10,3 @@ "main": "dist/index-node-cjs.cjs",

".": {
"types": "./src/jsonpath.d.ts",
"browser": "./dist/index-browser-esm.js",

@@ -71,3 +72,3 @@ "umd": "./dist/index-browser-umd.cjs",

"coveradge": "^0.8.1",
"eslint": "^8.22.0",
"eslint": "^8.23.0",
"eslint-config-ash-nazg": "^34.1.0",

@@ -87,3 +88,3 @@ "eslint-config-standard": "^17.0.0",

"eslint-plugin-no-use-extend-native": "^0.5.0",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-promise": "^6.0.1",
"eslint-plugin-sonarjs": "^0.15.0",

@@ -98,6 +99,6 @@ "eslint-plugin-standard": "^4.1.0",

"open-cli": "^7.0.1",
"rollup": "2.78.1",
"rollup": "2.79.0",
"rollup-plugin-terser": "^7.0.2",
"typedoc": "^0.23.10",
"typescript": "^4.7.4"
"typedoc": "^0.23.13",
"typescript": "^4.8.2"
},

@@ -151,4 +152,3 @@ "keywords": [

"browser-test": "npm run eslint && npm run rollup && open-cli http://localhost:8084/test/ && npm start"
},
"readme": "[![npm](https://img.shields.io/npm/v/jsonpath-plus.svg)](https://www.npmjs.com/package/jsonpath-plus)\n[![Dependencies](https://img.shields.io/david/s3u/JSONPath.svg)](https://david-dm.org/s3u/JSONPath)\n[![devDependencies](https://img.shields.io/david/dev/s3u/JSONPath.svg)](https://david-dm.org/s3u/JSONPath?type=dev)\n\n[![testing badge](https://raw.githubusercontent.com/s3u/JSONPath/master/badges/tests-badge.svg?sanitize=true)](badges/tests-badge.svg)\n[![coverage badge](https://raw.githubusercontent.com/s3u/JSONPath/master/badges/coverage-badge.svg?sanitize=true)](badges/coverage-badge.svg)\n\n[![Known Vulnerabilities](https://snyk.io/test/github/s3u/JSONPath/badge.svg)](https://snyk.io/test/github/s3u/JSONPath)\n[![Total Alerts](https://img.shields.io/lgtm/alerts/g/s3u/JSONPath.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/s3u/JSONPath/alerts)\n[![Code Quality: Javascript](https://img.shields.io/lgtm/grade/javascript/g/s3u/JSONPath.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/s3u/JSONPath/context:javascript)\n\n<!--[![License](https://img.shields.io/npm/l/JSONPath.svg)](LICENSE-MIT.txt)-->\n[![Licenses badge](https://raw.githubusercontent.com/s3u/JSONPath/master/badges/licenses-badge.svg?sanitize=true)](badges/licenses-badge.svg)\n\n<small>(see also [licenses for dev. deps.](https://raw.githubusercontent.com/s3u/JSONPath/master/badges/licenses-badge-dev.svg?sanitize=true))</small>\n\n# JSONPath Plus [![Node.js CI status](https://github.com/git://github.com/s3u/JSONPath.git/workflows/Node.js%20CI/badge.svg)](https://github.com/git://github.com/s3u/JSONPath.git/actions)\n\nAnalyse, transform, and selectively extract data from JSON\ndocuments (and JavaScript objects).\n\n`jsonpath-plus` expands on the original specification to add some\nadditional operators and makes explicit some behaviors the original\ndid not spell out.\n\nTry the [browser demo](https://jsonpath-plus.github.io/JSONPath/demo/) or\n[Runkit (Node)](https://npm.runkit.com/jsonpath-plus).\n\n***Please note: This project is not currently being actively maintained. We\nmay accept well-documented PRs or some simple updates, but are not looking\nto make fixes or add new features ourselves.***\n\n## Features\n\n* **Compliant** with the original jsonpath spec\n* Convenient **additions or elaborations** not provided in the original spec:\n * `^` for grabbing the **parent** of a matching item\n * `~` for grabbing **property names** of matching items (as array)\n * **Type selectors** for obtaining:\n * Basic JSON types: `@null()`, `@boolean()`, `@number()`, `@string()`, `@array()`, `@object()`\n * `@integer()`\n * The compound type `@scalar()` (which also accepts `undefined` and\n non-finite numbers when querying JavaScript objects as well as all of the basic non-object/non-function types)\n * `@other()` usable in conjunction with a user-defined `otherTypeCallback`\n * Non-JSON types that can nevertheless be used when querying\n non-JSON JavaScript objects (`@undefined()`, `@function()`, `@nonFinite()`)\n * `@path`/`@parent`/`@property`/`@parentProperty`/`@root` **shorthand selectors** within filters\n * **Escaping**\n * `` ` `` for escaping remaining sequence\n * `@['...']`/`?@['...']` syntax for escaping special characters within\n property names in filters\n * Documents `$..` (**getting all parent components**)\n* **ESM** and **UMD** export formats\n* In addition to queried values, **can return various meta-information**\n including paths or pointers to the value, as well as the parent\n object and parent property name (to allow for modification).\n* **Utilities for converting** between paths, arrays, and pointers\n* Option to **prevent evaluations** permitted in the original spec or supply\n a **sandbox** for evaluated values.\n* Option for **callback to handle results** as they are obtained.\n\n## Benchmarking\n\n`jsonpath-plus` is consistently performant with both large and small datasets compared to other json querying libraries per [json-querying-performance-testing](https://github.com/andykais/json-querying-performance-testing). You can verify these findings by [running the project yourself](https://github.com/andykais/json-querying-performance-testing#how-to-run) and adding more perf cases.\n\n## Install\n\n```shell\nnpm install jsonpath-plus\n```\n\n## Setup\n\n### Node.js\n\n```js\nconst {JSONPath} = require('jsonpath-plus');\n\nconst result = JSONPath({path: '...', json});\n```\n\n### Browser\n\nFor browser usage you can directly include `dist/index-browser-umd.cjs`; no\nBrowserify magic is necessary:\n\n```html\n<!-- Polyfill recommended by Babel for items not covered for older\n browsers in dist -->\n<script src=\"node_modules/core-js-bundle/minified.js\"></script>\n\n<script src=\"node_modules/jsonpath-plus/dist/index-browser-umd.cjs\"></script>\n\n<script>\n\nconst result = JSONPath.JSONPath({path: '...', json: {}});\n\n</script>\n```\n\n### ESM (Modern browsers)\n\nYou may also use ES6 Module imports (for modern browsers):\n\n```html\n<script type=\"module\">\n\nimport {\n JSONPath\n} from './node_modules/jsonpath-plus/dist/index-browser-esm.js';\n\nconst result = JSONPath({path: '...', json: {}});\n\n</script>\n```\n\n### ESM (Bundlers)\n\nOr if you are bundling your JavaScript (e.g., with Rollup), just use,\nnoting that [`mainFields`](https://github.com/rollup/plugins/tree/master/packages/node-resolve#mainfields)\nshould include `browser` for browser builds (for Node, the default, which\nchecks `module`, should be fine):\n\n```js\nimport {JSONPath} from 'jsonpath-plus';\n\nconst result = JSONPath({path: '...', json});\n```\n\n## Usage\n\nThe full signature available is:\n\n```\nconst result = JSONPath([options,] path, json, callback, otherTypeCallback);\n```\n\nThe arguments `path`, `json`, `callback`, and `otherTypeCallback`\ncan alternatively be expressed (along with any other of the\navailable properties) on `options`.\n\nNote that `result` will contain all items found (optionally\nwrapped into an array) whereas `callback` can be used if you\nwish to perform some operation as each item is discovered, with\nthe callback function being executed 0 to N times depending\non the number of independent items to be found in the result.\nSee the docs below for more on `JSONPath`'s available arguments.\n\nSee also the [API docs](https://jsonpath-plus.github.io/JSONPath/docs/ts/).\n\n### Properties\n\nThe properties that can be supplied on the options object or\nevaluate method (as the first argument) include:\n\n- ***path*** (**required**) - The JSONPath expression as a (normalized\n or unnormalized) string or array\n- ***json*** (**required**) - The JSON object to evaluate (whether of\n null, boolean, number, string, object, or array type).\n- ***autostart*** (**default: true**) - If this is supplied as `false`,\n one may call the `evaluate` method manually.\n- ***flatten*** (**default: false**) - Whether the returned array of results\n will be flattened to a single dimension array.\n- ***resultType*** (**default: \"value\"**) - Can be case-insensitive form of\n \"value\", \"path\", \"pointer\", \"parent\", or \"parentProperty\" to determine\n respectively whether to return results as the values of the found items,\n as their absolute paths, as [JSON Pointers](https://tools.ietf.org/html/rfc6901)\n to the absolute paths, as their parent objects, or as their parent's\n property name. If set to \"all\", all of these types will be returned on\n an object with the type as key name.\n- ***sandbox*** (**default: {}**) - Key-value map of variables to be\n available to code evaluations such as filtering expressions. (Note\n that the current path and value will also be available to those\n expressions; see the Syntax section for details.)\n- ***wrap*** (**default: true**) - Whether or not to wrap the results\n in an array. If `wrap` is set to `false`, and no results are found,\n `undefined` will be returned (as opposed to an empty array when\n `wrap` is set to true). If `wrap` is set to `false` and a single\n non-array result is found, that result will be the only item returned\n (not within an array). An array will still be returned if multiple\n results are found, however. To avoid ambiguities (in the case where\n it is necessary to distinguish between a result which is a failure\n and one which is an empty array), it is recommended to switch the\n default to `false`.\n- ***preventEval*** (**default: false**) - Although JavaScript evaluation\n expressions are allowed by default, for security reasons (if one is\n operating on untrusted user input, for example), one may wish to\n set this option to `true` to throw exceptions when these expressions\n are attempted.\n- ***parent*** (**default: null**) - In the event that a query could be\n made to return the root node, this allows the parent of that root node\n to be returned within results.\n- ***parentProperty*** (**default: null**) - In the event that a query\n could be made to return the root node, this allows the `parentProperty`\n of that root node to be returned within results.\n- ***callback*** (**default: (none)**) - If supplied, a callback will be\n called immediately upon retrieval of an end point value. The three arguments\n supplied will be the value of the payload (according to `resultType`),\n the type of the payload (whether it is a normal \"value\" or a \"property\"\n name), and a full payload object (with all `resultType`s).\n- ***otherTypeCallback*** (**default: \\<A function that throws an error**\n **when @other() is encountered\\>**) - In the current absence of JSON\n Schema support, one can determine types beyond the built-in types by\n adding the operator `@other()` at the end of one's query. If such a\n path is encountered, the `otherTypeCallback` will be invoked with the\n value of the item, its path, its parent, and its parent's property name,\n and it should return a boolean indicating whether the supplied value\n belongs to the \"other\" type or not (or it may handle transformations and\n return false).\n\n### Instance methods\n\n- ***evaluate(path, json, callback, otherTypeCallback)*** OR\n ***evaluate({path: \\<path\\>, json: \\<json object\\>, callback:***\n ***\\<callback function\\>, otherTypeCallback:***\n ***\\<otherTypeCallback function\\>})*** - This method is only\n necessary if the `autostart` property is set to `false`. It\n can be used for repeated evaluations using the same configuration.\n Besides the listed properties, the latter method pattern can\n accept any of the other allowed instance properties (except\n for `autostart` which would have no relevance here).\n\n### Class properties and methods\n\n- ***JSONPath.cache*** - Exposes the cache object for those who wish\n to preserve and reuse it for optimization purposes.\n- ***JSONPath.toPathArray(pathAsString)*** - Accepts a normalized or\n unnormalized path as string and converts to an array: for\n example, `['$', 'aProperty', 'anotherProperty']`.\n- ***JSONPath.toPathString(pathAsArray)*** - Accepts a path array and\n converts to a normalized path string. The string will be in a form\n like: `$['aProperty']['anotherProperty][0]`. The JSONPath terminal\n constructions `~` and `^` and type operators like `@string()` are\n silently stripped.\n- ***JSONPath.toPointer(pathAsArray)*** - Accepts a path array and\n converts to a [JSON Pointer](https://tools.ietf.org/html/rfc6901).\n The string will be in a form like: `/aProperty/anotherProperty/0`\n (with any `~` and `/` internal characters escaped as per the JSON\n Pointer spec). The JSONPath terminal constructions `~` and `^` and\n type operators like `@string()` are silently stripped.\n\n## Syntax through examples\n\nGiven the following JSON, taken from <http://goessner.net/articles/JsonPath/>:\n\n```json\n{\n\"store\": {\n \"book\": [\n {\n \"category\": \"reference\",\n \"author\": \"Nigel Rees\",\n \"title\": \"Sayings of the Century\",\n \"price\": 8.95\n },\n {\n \"category\": \"fiction\",\n \"author\": \"Evelyn Waugh\",\n \"title\": \"Sword of Honour\",\n \"price\": 12.99\n },\n {\n \"category\": \"fiction\",\n \"author\": \"Herman Melville\",\n \"title\": \"Moby Dick\",\n \"isbn\": \"0-553-21311-3\",\n \"price\": 8.99\n },\n {\n \"category\": \"fiction\",\n \"author\": \"J. R. R. Tolkien\",\n \"title\": \"The Lord of the Rings\",\n \"isbn\": \"0-395-19395-8\",\n \"price\": 22.99\n }\n ],\n \"bicycle\": {\n \"color\": \"red\",\n \"price\": 19.95\n }\n}\n}\n```\n\nand the following XML representation:\n\n```xml\n<store>\n <book>\n <category>reference</category>\n <author>Nigel Rees</author>\n <title>Sayings of the Century</title>\n <price>8.95</price>\n </book>\n <book>\n <category>fiction</category>\n <author>Evelyn Waugh</author>\n <title>Sword of Honour</title>\n <price>12.99</price>\n </book>\n <book>\n <category>fiction</category>\n <author>Herman Melville</author>\n <title>Moby Dick</title>\n <isbn>0-553-21311-3</isbn>\n <price>8.99</price>\n </book>\n <book>\n <category>fiction</category>\n <author>J. R. R. Tolkien</author>\n <title>The Lord of the Rings</title>\n <isbn>0-395-19395-8</isbn>\n <price>22.99</price>\n </book>\n <bicycle>\n <color>red</color>\n <price>19.95</price>\n </bicycle>\n</store>\n```\n\nPlease note that the XPath examples below do not distinguish between\nretrieving elements and their text content (except where useful for\ncomparisons or to prevent ambiguity). Note: to test the XPath examples\n(including 2.0 ones), [this demo](http://videlibri.sourceforge.net/cgi-bin/xidelcgi)\nmay be helpful (set to `xml` or `xml-strict`).\n\n| XPath | JSONPath | Result | Notes |\n| ----------------- | ---------------------- | ------------------------------------- | ----- |\n/store/book/author | $.store.book\\[*].author | The authors of all books in the store | Can also be represented without the `$.` as `store.book[*].author` (though this is not present in the original spec); note that some character literals (`$` and `@`) require escaping, however\n//author | $..author | All authors |\n/store/* | $.store.* | All things in store, which are its books (a book array) and a red bicycle (a bicycle object).|\n/store//price | $.store..price | The price of everything in the store. |\n//book\\[3] | $..book\\[2] | The third book (book object) |\n//book\\[last()] | $..book\\[(@.length-1)]<br>$..book\\[-1:] | The last book in order.| To access a property with a special character, utilize `[(@['...'])]` for the filter (this particular feature is not present in the original spec)\n//book\\[position()<3]| $..book\\[0,1]<br>$..book\\[:2]| The first two books |\n//book/*\\[self::category\\|self::author] or //book/(category,author) in XPath 2.0 | $..book\\[0]\\[category,author]| The categories and authors of all books |\n//book\\[isbn] | $..book\\[?(@.isbn)] | Filter all books with an ISBN number | To access a property with a special character, utilize `[?@['...']]` for the filter (this particular feature is not present in the original spec)\n//book\\[price<10] | $..book\\[?(@.price<10)] | Filter all books cheaper than 10 |\n| //\\*\\[name() = 'price' and . != 8.95] | $..\\*\\[?(@property === 'price' && @ !== 8.95)] | Obtain all property values of objects whose property is price and which does not equal 8.95 | With the bare `@` allowing filtering objects by property value (not necessarily within arrays), you can add `^` after the expression to get at the object possessing the filtered properties\n/ | $ | The root of the JSON object (i.e., the whole object itself) | To get a literal `$` (by itself or anywhere in the path), you must use the backtick escape\n//\\*/\\*\\|//\\*/\\*/text() | $..* | All Elements (and text) beneath root in an XML document. All members of a JSON structure beneath the root. |\n//* | $.. | All Elements in an XML document. All parent components of a JSON structure including root. | This behavior was not directly specified in the original spec\n//*\\[price>19]/.. | $..\\[?(@.price>19)]^ | Parent of those specific items with a price greater than 19 (i.e., the store value as the parent of the bicycle and the book array as parent of an individual book) | Parent (caret) not present in the original spec\n/store/*/name() (in XPath 2.0) | $.store.*~ | The property names of the store sub-object (\"book\" and \"bicycle\"). Useful with wildcard properties. | Property name (tilde) is not present in the original spec\n/store/book\\[not(. is /store/book\\[1\\])\\] (in XPath 2.0) | $.store.book\\[?(@path !== \"$\\[\\'store\\']\\[\\'book\\']\\[0]\")] | All books besides that at the path pointing to the first | @path not present in the original spec\n//book\\[parent::\\*/bicycle/color = \"red\"]/category | $..book\\[?(@parent.bicycle && @parent.bicycle.color === \"red\")].category | Grabs all categories of books where the parent object of the book has a bicycle child whose color is red (i.e., all the books) | @parent is not present in the original spec\n//book/*\\[name() != 'category'] | $..book.*\\[?(@property !== \"category\")] | Grabs all children of \"book\" except for \"category\" ones | @property is not present in the original spec\n//book\\[position() != 1] | $..book\\[?(@property !== 0)] | Grabs all books whose property (which, being that we are reaching inside an array, is the numeric index) is not 0 | @property is not present in the original spec\n/store/\\*/\\*\\[name(parent::*) != 'book'] | $.store.*\\[?(@parentProperty !== \"book\")] | Grabs the grandchildren of store whose parent property is not book (i.e., bicycle's children, \"color\" and \"price\") | @parentProperty is not present in the original spec\n//book\\[count(preceding-sibling::\\*) != 0]/\\*/text() | $..book.*\\[?(@parentProperty !== 0)] | Get the property values of all book instances whereby the parent property of these values (i.e., the array index holding the book item parent object) is not 0 | @parentProperty is not present in the original spec\n//book\\[price = /store/book\\[3]/price] | $..book\\[?(@.price === @root.store.book\\[2].price)] | Filter all books whose price equals the price of the third book | @root is not present in the original spec\n//book/../\\*\\[. instance of element(\\*, xs:decimal)\\] (in XPath 2.0) | $..book..\\*@number() | Get the numeric values within the book array | @number(), the other basic types (@boolean(), @string()), other low-level derived types (@null(), @object(), @array()), the JSONSchema-added type, @integer(), the compound type @scalar() (which also accepts `undefined` and non-finite numbers for JavaScript objects as well as all of the basic non-object/non-function types), the type, @other(), to be used in conjunction with a user-defined callback (see `otherTypeCallback`) and the following non-JSON types that can nevertheless be used with JSONPath when querying non-JSON JavaScript objects (@undefined(), @function(), @nonFinite()) are not present in the original spec\n//book/*[name() = 'category' and matches(., 'tion$')] (XPath 2.0) | $..book.*\\[?(@property === \"category\" && @.match(/TION$/i))] | All categories of books which match the regex (end in 'TION' case insensitive) | @property is not present in the original spec.\n//book/*[matches(name(), 'bn$')]/parent::* (XPath 2.0) | $..book.*\\[?(@property.match(/bn$/i))]^ | All books which have a property matching the regex (end in 'TION' case insensitive) | @property is not present in the original spec. Note: Uses the parent selector \\^ at the end of the expression to return to the parent object; without the parent selector, it matches the two `isbn` key values.\n| | `` ` `` (e.g., `` `$`` to match a property literally named `$`) | Escapes the entire sequence following (to be treated as a literal) | `` ` `` is not present in the original spec; to get a literal backtick, use an additional backtick to escape\n\nAny additional variables supplied as properties on the optional \"sandbox\"\nobject option are also available to (parenthetical-based)\nevaluations.\n\n## Potential sources of confusion for XPath users\n\n1. In JSONPath, a filter expression, in addition to its `@` being a\nreference to its children, actually selects the immediate children\nas well, whereas in XPath, filter conditions do not select the children\nbut delimit which of its parent nodes will be obtained in the result.\n1. In JSONPath, array indexes are, as in JavaScript, 0-based (they begin\nfrom 0), whereas in XPath, they are 1-based.\n1. In JSONPath, equality tests utilize (as per JavaScript) multiple equal signs\nwhereas in XPath, they use a single equal sign.\n\n## Ideas\n\n1. Support OR outside of filters (as in XPath `|`) and grouping.\n1. Create syntax to work like XPath filters in not selecting children?\n1. Allow option for parentNode equivalent (maintaining entire chain of\n parent-and-parentProperty objects up to root)\n\n## Development\n\nRunning the tests on Node:\n\n```shell\nnpm test\n```\n\nFor in-browser tests:\n\n- Serve the js/html files:\n\n```shell\nnpm run browser-test\n```\n\n- Visit [http://localhost:8082/test/](http://localhost:8082/test/).\n\n## License\n\n[MIT License](http://www.opensource.org/licenses/mit-license.php).\n"
}
}

@@ -355,9 +355,7 @@ const {hasOwnProperty: hasOwnProp} = Object.prototype;

} else if (loc === '*') { // all child properties
this._walk(
loc, x, val, path, parent, parentPropName, callback,
(m, l, _x, v, p, par, pr, cb) => {
addRet(this._trace(unshift(m, _x), v, p, par, pr, cb,
true, true));
}
);
this._walk(val, (m) => {
addRet(this._trace(
x, val[m], push(path, m), val, m, callback, true, true
));
});
} else if (loc === '..') { // all descendent parent properties

@@ -369,16 +367,13 @@ // Check remaining expression with val's immediate children

);
this._walk(
loc, x, val, path, parent, parentPropName, callback,
(m, l, _x, v, p, par, pr, cb) => {
// We don't join m and x here because we only want parents,
// not scalar values
if (typeof v[m] === 'object') {
// Keep going with recursive descent on val's
// object children
addRet(this._trace(
unshift(l, _x), v[m], push(p, m), v, m, cb, true
));
}
this._walk(val, (m) => {
// We don't join m and x here because we only want parents,
// not scalar values
if (typeof val[m] === 'object') {
// Keep going with recursive descent on val's
// object children
addRet(this._trace(
expr.slice(), val[m], push(path, m), val, m, callback, true
));
}
);
});
// The parent sel computation is handled in the frame above using the

@@ -413,11 +408,9 @@ // ancestor object of val

}
this._walk(
loc, x, val, path, parent, parentPropName, callback,
(m, l, _x, v, p, par, pr, cb) => {
if (this._eval(l.replace(/^\?\((.*?)\)$/u, '$1'), v[m], m, p, par, pr)) {
addRet(this._trace(unshift(m, _x), v, p, par, pr, cb,
true));
}
const safeLoc = loc.replace(/^\?\((.*?)\)$/u, '$1');
this._walk(val, (m) => {
if (this._eval(safeLoc, val[m], m, path, parent, parentPropName)) {
addRet(this._trace(x, val[m], push(path, m), val, m, callback,
true));
}
);
});
} else if (loc[0] === '(') { // [(expr)] (dynamic property/index)

@@ -549,13 +542,11 @@ if (this.currPreventEval) {

JSONPath.prototype._walk = function (
loc, expr, val, path, parent, parentPropName, callback, f
) {
JSONPath.prototype._walk = function (val, f) {
if (Array.isArray(val)) {
const n = val.length;
for (let i = 0; i < n; i++) {
f(i, loc, expr, val, path, parent, parentPropName, callback);
f(i);
}
} else if (val && typeof val === 'object') {
Object.keys(val).forEach((m) => {
f(m, loc, expr, val, path, parent, parentPropName, callback);
f(m);
});

@@ -562,0 +553,0 @@ }

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc