Security News
The Unpaid Backbone of Open Source: Solo Maintainers Face Increasing Security Demands
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
jsonpath-plus
Advanced tools
The jsonpath-plus npm package allows users to query and manipulate JSON documents using the JSONPath query language. It provides capabilities to extract data from JSON structures, manipulate the data, and even transform JSON data based on specific queries.
Querying JSON
This feature allows users to extract data from a JSON document based on a specified JSONPath query. The example provided demonstrates how to retrieve all authors from a list of books in a store.
const {JSONPath} = require('jsonpath-plus');
const result = JSONPath({path: '$.store.book[*].author', json: jsonDocument});
console.log(result);
Filtering results
This feature enables filtering elements of a JSON document that meet certain conditions. In the example, it filters books that have a price less than 10.
const {JSONPath} = require('jsonpath-plus');
const result = JSONPath({path: '$.store.book[?(@.price < 10)].title', json: jsonDocument});
console.log(result);
Using script expressions
This feature supports the use of script expressions within the JSONPath query to perform more complex queries. The example fetches the title of the last book in the list.
const {JSONPath} = require('jsonpath-plus');
const result = JSONPath({path: '$.store.book[(@.length-1)].title', json: jsonDocument});
console.log(result);
The jsonpath package also allows for querying JSON documents using JSONPath syntax. It is similar to jsonpath-plus but lacks some of the extended features like script expressions and is not as actively maintained.
Object-path is another package that provides access to values deep within a JSON object using a simple path notation. It is less focused on the JSONPath standard and more on providing a straightforward way to access and set deep values.
JMESPath is a query language for JSON that allows similar functionalities to JSONPath. It is different in its syntax and approach but serves a similar purpose of querying and transforming JSON data. It is widely used in AWS services.
Analyse, transform, and selectively extract data from JSON documents (and JavaScript objects).
npm install jsonpath-plus
In node.js:
var JSONPath = require('jsonpath-plus');
JSONPath({json: obj, path: path, callback: callback});
For browser usage you can directly include lib/jsonpath.js
, no browserify
magic necessary:
<script src="lib/jsonpath.js"></script>
<script>
JSONPath({path: path, json: obj, callback: callback, otherTypeCallback: otherTypeCallback});
</script>
An alternative syntax is available as:
JSONPath([options,] path, obj, callback, otherTypeCallback);
The following format is now deprecated:
jsonPath.eval(options, obj, path);
The properties that can be supplied on the options object or evaluate method (as the first argument) include:
false
, one may call the evaluate
method manually.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.true
to throw exceptions when these expressions are attempted.resultType
), the type of the payload (whether it is a normal "value" or a "property" name), and a full payload object (with all resultType
s).@other()
at the end of one's query. If such a path is encountered, the otherTypeCallback
will be invoked with the value of the item, its path, its parent, and its parent's property name, and it should return a boolean indicating whether the supplied value belongs to the "other" type or not (or it may handle transformations and return false).autostart
property is set to false
. It can be used for repeated evaluations using the same configuration. Besides the listed properties, the latter method pattern can accept any of the other allowed instance properties (except for autostart
which would have no relevance here).['$', 'aProperty', 'anotherProperty']
.$['aProperty']['anotherProperty][0]
. The JSONPath terminal constructions ~
and ^
and type operators like @string()
are silently stripped.'/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.Given the following JSON, taken from http://goessner.net/articles/JsonPath/ :
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
and the following XML representation:
<store>
<book>
<category>reference</category>
<author>Nigel Rees</author>
<title>Sayings of the Century</title>
<price>8.95</price>
</book>
<book>
<category>fiction</category>
<author>Evelyn Waugh</author>
<title>Sword of Honour</title>
<price>12.99</price>
</book>
<book>
<category>fiction</category>
<author>Herman Melville</author>
<title>Moby Dick</title>
<isbn>0-553-21311-3</isbn>
<price>8.99</price>
</book>
<book>
<category>fiction</category>
<author>J. R. R. Tolkien</author>
<title>The Lord of the Rings</title>
<isbn>0-395-19395-8</isbn>
<price>22.99</price>
</book>
<bicycle>
<color>red</color>
<price>19.95</price>
</bicycle>
</store>
Please note that the XPath examples below do not distinguish between retrieving elements and their text content (except where useful for comparisons or to prevent ambiguity).
XPath | JSONPath | Result | Notes |
---|---|---|---|
/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 | |
/store/* | $.store.* | All things in store, which are its books (a book array) and a red bicycle (a bicycle object). | |
/store//price | $.store..price | The price of everything in the store. | |
//book[3] | $..book[2] | The third book (book object) | |
//book[last()] | $..book[(@.length-1)] $..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] $..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 | 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 | |
//*[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 | |
/ | $ | The root of the JSON object (i.e., the whole object itself) | |
//*/*|//*/*/text() | $..* | All Elements (and text) beneath root in an XML document. All members of a JSON structure beneath the root. | |
//* | $.. | 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 |
//*[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 documented in the original spec |
/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 |
/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 |
//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 |
//book/*[name() != 'category'] | $..book.*[?(@property !== "category")] | Grabs all children of "book" except for "category" ones | @property is not present in the original spec |
//book/*[position() != 0] | $..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 |
/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 |
//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 |
//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 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 |
Any additional variables supplied as properties on the optional "sandbox" object option are also available to (parenthetical-based) evaluations.
@
being a
reference to its children, actually selects the immediate children
as well, whereas in XPath, filter conditions do not select the children
but delimit which of its parent nodes will be obtained in the result.|
) and grouping.Running the tests on node: npm test
. For in-browser tests:
cd node_modules/nodeunit; make browser;
node -e "require('http').createServer(function(req,res) { \
var s = require('fs').createReadStream('.' + req.url); \
s.pipe(res); s.on('error', function() {}); }).listen(8082);"
0.13.0 (Dec 13, 2015)
~
and ^
operators
and type operators such as @string()
in JSONPath.toPathString()
calls.Array.isArray
polyfill as no longer
supporting IE <= 8JSONPath
JSONPath.toPointer()
and "pointer" resultType
option.callback
and otherTypeCallback
as numbered
arguments to JSONPath
.@
or other special characters in at-sign-prefixed
property names (by use of [?(@['...'])]
or [(@['...'])]
).FAQs
A JS implementation of JSONPath with some additional operators
The npm package jsonpath-plus receives a total of 2,786,788 weekly downloads. As such, jsonpath-plus popularity was classified as popular.
We found that jsonpath-plus demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Solo open source maintainers face burnout and security challenges, with 60% unpaid and 60% considering quitting.
Security News
License exceptions modify the terms of open source licenses, impacting how software can be used, modified, and distributed. Developers should be aware of the legal implications of these exceptions.
Security News
A developer is accusing Tencent of violating the GPL by modifying a Python utility and changing its license to BSD, highlighting the importance of copyleft compliance.