Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

jsonpath-plus

Package Overview
Dependencies
Maintainers
1
Versions
43
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 0.12.0 to 0.13.0

.eslintrc.json

13

CHANGES.md

@@ -0,1 +1,14 @@

## ?
## Dec 13, 2015
- Breaking change (from version 0.11): Silently strip `~` and `^` operators and type operators such as `@string()` in `JSONPath.toPathString()` calls.
- Breaking change: Remove `Array.isArray` polyfill as longer supporting IE <= 8
- Feature: Allow omission of options first argument to `JSONPath`
- Feature: Add `JSONPath.toPointer()` and "pointer" `resultType` option.
- Fix: Correctly support `callback` and `otherTypeCallback` as numbered arguments to `JSONPath`.
- Fix: Enhance Node checking to avoid issue reported with angular-mock
- Fix: Allow for `@` or other special characters in at-sign-prefixed property names (by use of `[?(@['...'])]` or `[(@['...'])]`).
- Version 0.13.0
## Dec 12, 2015 10:39pm

@@ -2,0 +15,0 @@ - Breaking change: Problems with upper-case letters in npm is causing us to rename the package, so have renamed package to "jsonpath-plus" (there are already package with lower-case "jsonpath" or "json-path"). The new name also reflects that

104

lib/jsonpath.js

@@ -1,3 +0,3 @@

/*global module, exports, require*/
/*jslint vars:true, evil:true*/
/*global exports, require*/
/* eslint-disable no-eval */
/* JSONPath 0.8.0 - XPath for JSON

@@ -9,19 +9,13 @@ *

var module;
(function (require) {'use strict';
// Keep compatibility with old browsers
if (!Array.isArray) {
Array.isArray = function (vArg) {
return Object.prototype.toString.call(vArg) === '[object Array]';
};
}
// Make sure to know if we are in real node or not (the `require` variable
// could actually be require.js, for example.
var isNode = typeof module !== 'undefined' && !!module.exports;
var isNode = module && !!module.exports;
var allowedResultTypes = ['value', 'path', 'parent', 'parentProperty', 'all'];
var allowedResultTypes = ['value', 'path', 'pointer', 'parent', 'parentProperty', 'all'];
var vm = isNode ?
require('vm') : {
var vm = isNode
? require('vm') : {
runInNewContext: function (expr, context) {

@@ -39,7 +33,12 @@ return eval(Object.keys(context).reduce(function (s, vr) {

function unshift (elem, arr) {arr = arr.slice(); arr.unshift(elem); return arr;}
function NewError (value) {
this.avoidNew = true;
this.value = value;
this.message = 'JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)';
}
function JSONPath (opts, expr, obj, callback) {
function JSONPath (opts, expr, obj, callback, otherTypeCallback) {
if (!(this instanceof JSONPath)) {
try {
return new JSONPath(opts, expr, obj, callback);
return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
}

@@ -54,2 +53,9 @@ catch (e) {

if (typeof opts === 'string') {
otherTypeCallback = callback;
callback = obj;
obj = expr;
expr = opts;
opts = {};
}
opts = opts || {};

@@ -66,5 +72,5 @@ var objArgs = opts.hasOwnProperty('json') && opts.hasOwnProperty('path');

this.parentProperty = opts.parentProperty || null;
this.callback = opts.callback || null;
this.otherTypeCallback = opts.otherTypeCallback || function () {
throw "You must supply an otherTypeCallback callback option with the @other() operator.";
this.callback = opts.callback || callback || null;
this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function () {
throw new Error('You must supply an otherTypeCallback callback option with the @other() operator.');
};

@@ -78,3 +84,3 @@

if (!ret || typeof ret !== 'object') {
throw {avoidNew: true, value: ret, message: "JSONPath should not be called with 'new' (it prevents return of (unwrapped) scalar values)"};
throw new NewError(ret);
}

@@ -104,3 +110,3 @@ return ret;

if (!expr.path) {
throw "You must supply a 'path' property when providing an object argument to JSONPath.evaluate().";
throw new Error('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');
}

@@ -133,3 +139,3 @@ json = expr.hasOwnProperty('json') ? expr.json : json;

var result = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback);
result = result.filter(function (ea) { return ea && !ea.isParentSelector; });
result = result.filter(function (ea) {return ea && !ea.isParentSelector;});

@@ -152,3 +158,2 @@ if (!result.length) {return wrap ? [] : undefined;}

// PRIVATE METHODS

@@ -166,2 +171,4 @@

return JSONPath.toPathString(ea[resultType]);
case 'pointer':
return JSONPath.toPointer(ea.path);
}

@@ -194,3 +201,3 @@ };

if (val && val.hasOwnProperty(loc)) { // simple case--directly follow property
if (val && Object.prototype.hasOwnProperty.call(val, loc)) { // simple case--directly follow property
addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback));

@@ -214,3 +221,3 @@ }

if (this.currPreventEval) {
throw "Eval [(expr)] prevented in JSONPath expression.";
throw new Error('Eval [(expr)] prevented in JSONPath expression.');
}

@@ -240,3 +247,3 @@ // As this will resolve to a property name (but we don't know it yet), property and parent information is relative to the parent of the property to which this expression will resolve

if (this.currPreventEval) {
throw "Eval [?(expr)] prevented in JSONPath expression.";
throw new Error('Eval [?(expr)] prevented in JSONPath expression.');
}

@@ -325,3 +332,3 @@ this._walk(loc, x, val, path, parent, parentPropName, callback, function (m, l, x, v, p, par, pr, cb) {

for (m in val) {
if (val.hasOwnProperty(m)) {
if (Object.prototype.hasOwnProperty.call(val, m)) {
f(m, loc, expr, val, path, parent, parentPropName, callback);

@@ -341,3 +348,3 @@ }

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 = [];

@@ -368,5 +375,5 @@ for (i = start; i < end; i += step) {

}
if (code.indexOf('@') > -1) {
if (code.match(/@([\.\s\)\[])/)) {
this.currSandbox._$_v = _v;
code = code.replace(/@/g, '_$_v');
code = code.replace(/@([\.\s\)\[])/g, '_$_v$1');
}

@@ -376,3 +383,3 @@ try {

}
catch(e) {
catch (e) {
console.log(e);

@@ -391,3 +398,5 @@ throw new Error('jsonPath: ' + e.message + ': ' + code);

for (i = 1, n = x.length; i < n; i++) {
p += (/~|@.*\(\)/).test(x[i]) ? x[i] : ((/^[0-9*]+$/).test(x[i]) ? ('[' + x[i] + ']') : ("['" + x[i] + "']"));
if (!(/^(~|\^|@.*?\(\))$/).test(x[i])) {
p += (/^[0-9*]+$/).test(x[i]) ? ('[' + x[i] + ']') : ("['" + x[i] + "']");
}
}

@@ -397,2 +406,14 @@ return p;

JSONPath.toPointer = function (pointer) {
var i, n, x = pointer, p = '';
for (i = 1, n = x.length; i < n; i++) {
if (!(/^(~|\^|@.*?\(\))$/).test(x[i])) {
p += '/' + x[i].toString()
.replace(/\~/g, '~0')
.replace(/\//g, '~1');
}
}
return p;
};
JSONPath.toPathArray = function (expr) {

@@ -405,9 +426,10 @@ var cache = JSONPath.cache;

.replace(/@(?:null|boolean|number|string|array|object|integer|undefined|nonFinite|function|other)\(\)/g, ';$&;')
.replace(/~/g, ';~;')
// Parenthetical evaluations (filtering and otherwise), directly within brackets or single quotes
.replace(/[\['](\??\(.*?\))[\]']/g, function ($0, $1) {return '[#' + (subx.push($1) - 1) + ']';})
// Escape periods within properties
// Escape periods and tildes within properties
.replace(/\['([^'\]]*)'\]/g, function ($0, prop) {
return "['" + prop.replace(/\./g, '%@%') + "']";
return "['" + prop.replace(/\./g, '%@%').replace(/~/g, '%%@@%%') + "']";
})
// Properties operator
.replace(/~/g, ';~;')
// Split by property boundaries

@@ -417,2 +439,4 @@ .replace(/'?\.'?(?![^\[]*\])|\['?/g, ';')

.replace(/%@%/g, '.')
// Reinsert tildes within properties
.replace(/%%@@%%/g, '~')
// Parent

@@ -424,2 +448,3 @@ .replace(/(?:;)?(\^+)(?:;)?/g, function ($0, ups) {return ';' + ups.split('').join(';') + ';';})

.replace(/;$|'?\]|'$/g, '');
var exprList = normalized.split(';').map(function (expr) {

@@ -439,5 +464,8 @@ var match = expr.match(/#([0-9]+)/);

if (typeof define === 'function' && define.amd) {
define(function() {return JSONPath;});
define(function () {return JSONPath;});
}
else if (typeof module === 'undefined') {
else if (isNode) {
module.exports = JSONPath;
}
else {
self.jsonPath = { // Deprecated

@@ -448,6 +476,2 @@ eval: JSONPath.eval

}
else {
module.exports = JSONPath;
}
}(typeof require === 'undefined' ? null : require));
{
"author": "Stefan Goessner",
"name": "jsonpath-plus",
"description": "A JS implementation of JSONPath",
"description": "A JS implementation of JSONPath with some additional operators",
"contributors": [

@@ -25,6 +25,10 @@ {

"email": "brettz9@yahoo.com"
},
{
"name": "Richard Schneider",
"email": "makaretu@gmail.com"
}
],
"license": "MIT",
"version": "0.12.0",
"version": "0.13.0",
"repository": {

@@ -38,7 +42,13 @@ "type": "git",

"dependencies": {},
"engines": {
"node": ">=0.8"
},
"devDependencies": {
"nodeunit": "0.9.0"
"nodeunit": "0.9.0",
"eslint": "^1.10.3",
"eslint-config-standard": "^4.4.0",
"eslint-plugin-standard": "^1.3.1"
},
"keywords": ["json", "jsonpath"],
"scripts": {"test": "./node_modules/.bin/nodeunit test"}
"scripts": {"test": "./node_modules/.bin/eslint test lib && \"./node_modules/.bin/nodeunit\" test"}
}

@@ -33,3 +33,3 @@ # JSONPath Plus [![build status](https://secure.travis-ci.org/s3u/JSONPath.png)](http://travis-ci.org/s3u/JSONPath)

```js
JSONPath(options, path, obj, callback, otherTypeCallback);
JSONPath([options,] path, obj, callback, otherTypeCallback);
```

@@ -51,3 +51,3 @@

- ***flatten*** (**default: false**) - Whether the returned array of results will be flattened to a single dimension array.
- ***resultType*** (**default: "value"**) - Can be case-insensitive form of "value", "path", "parent", or "parentProperty" to determine respectively whether to return results as the values of the found items, as their absolute paths, as their parent objects, or as their parent's property name. If set to "all", all of these types will be returned on an object with the type as key name.
- ***resultType*** (**default: "value"**) - Can be case-insensitive form of "value", "path", "pointer", "parent", or "parentProperty" to determine respectively whether to return results as the values of the found items, as their absolute paths, as [JSON Pointers](http://www.rfc-base.org/txt/rfc-6901.txt) to the absolute paths, as their parent objects, or as their parent's property name. If set to "all", all of these types will be returned on an object with the type as key name.
- ***sandbox*** (**default: {}**) - Key-value map of variables to be available to code evaluations such as filtering expressions. (Note that the current path and value will also be available to those expressions; see the Syntax section for details.)

@@ -69,3 +69,4 @@ - ***wrap*** (**default: true**) - Whether or not to wrap the results in an array. If `wrap` is set to false, and no results are found, `undefined` will be returned (as opposed to an empty array with `wrap` set to true). If `wrap` is set to false and a single result is found, that result will be the only item returned (not within an array). An array will still be returned if multiple results are found, however.

- ***JSONPath.toPathArray(pathAsString)*** - Accepts a normalized or unnormalized path as string and converts to an array: for example, `['$', 'aProperty', 'anotherProperty']`.
- ***JSONPath.toPathString(pathAsArray)*** - Accepts a path array and converts to a normalized path string. The string will be in form like: `$['aProperty']['anotherProperty]`. The terminal constructions `~` and typed operators like `@string()`, as with `$`, get added without enclosing single quotes and brackets.
- ***JSONPath.toPathString(pathAsArray)*** - Accepts a path array and converts to a normalized path string. The string will be in a form like: `$['aProperty']['anotherProperty][0]`. The JSONPath terminal constructions `~` and `^` and type operators like `@string()` are silently stripped.
- ***JSONPath.toPointer(pathAsArray)*** - Accepts a path array and converts to a [JSON Pointer](http://www.rfc-base.org/txt/rfc-6901.txt). The string will be in a form like: `'/aProperty/anotherProperty/0` (with any `~` and `/` internal characters escaped as per the JSON Pointer spec). The JSONPath terminal constructions `~` and `^` and type operators like `@string()` are silently stripped.

@@ -158,3 +159,3 @@ # Syntax through examples

------------------- | ---------------------- | ------------------------------------- | -----
/store/book/author | $.store.book[*].author | The authors of all books in the store |
/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)
//author | $..author | All authors |

@@ -164,6 +165,6 @@ /store/* | $.store.* | All things in store, which are its books (a book array) and a red bicycle (a bicycle object).|

//book[3] | $..book[2] | The third book (book object) |
//book[last()] | $..book[(@.length-1)]<br>$..book[-1:] | The last book in order.|
//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)
//book[position()<3]| $..book[0,1]<br>$..book[:2]| The first two books |
//book/*[self::category\|self::author] or //book/(category,author) in XPath 2.0 | $..book[0][category,author]| The categories and authors of all books |
//book[isbn] | $..book[?(@.isbn)] | Filter all books with an ISBN number |
//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)
//book[price<10] | $..book[?(@.price<10)] | Filter all books cheaper than 10 |

@@ -198,18 +199,8 @@ | //\*[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 |

# Todos
# Ideas
1. Conditionally resolve JSON references/JSON pointers instead or in
addition to raw retrieved data, with options on how deeply nested.
1. Support non-eval version (which supports parenthetical evaluations)
1. Support OR outside of filters (as in XPath `|`).
1. Support OR outside of filters (as in XPath `|`) and grouping.
1. Create syntax to work like XPath filters in not selecting children?
1. Allow for type-based searches to be JSON Schema aware (and allow
retrieval of schema segment for a given JSON fragment)
1. Pull or streaming parser?
1. Allow option for parentNode equivalent (maintaining entire chain of
parent-and-parentProperty objects up to root)
1. Fix in JSONPath to avoid need for `$`?
1. Define any allowed behaviors for: `$.`, `$[0]`, `$.[0]`, or `$.['prop']`
1. Modularize operator detection and usage to allow for
extensibility (at least non-standard ones)?
parent-and-parentProperty objects up to root)

@@ -216,0 +207,0 @@ # Development

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