JSON P3
JSONPath, JSON Pointer and JSON Patch for JavaScript.
JSONPath (RFC 9535) is a mini language for selecting values from JSON-like data. A JSONPath query has the potential to return multiple values from a data structure, along with their locations. This implementation is non-evaluating and read-only.
JSON Pointer (RFC 6901) is a syntax for targeting a single value in JSON-like data. JSON Pointers can be resolved against data to retrieve the value, or used as part of a JSON Patch operation.
JSON Patch (RFC 6902) is a standard for describing update operations to perform on JSON-like data. You can apply a patch to add, remove, replace, copy and move values within a JSON document.
We use the term JSON-like data to describe arbitrary, possibly nested, JavaScript arrays and objects, plus primitive strings, numbers, booleans and null, as you might expect from JSON.parse(). When traversing JSON-like data, we only resolve an object's direct properties, and the length property of arrays and strings is ignored.
Install
Node.js
Install JSON P3 using your preferred project manager:
- npm
- yarn
- pnpm
- bun
npm install --save json-p3
yarn add json-p3
pnpm add json-p3
bun add json-p3
And import the module:
- ESM
- CJS
import { jsonpath } from "json-p3";
const { jsonpath } = require("json-p3");
Example
This example uses a JSONPath expression to find users with a "pending" status, then builds a JSON Patch to change those user's status to "active". Note that jsonpatch.apply() updates data in place.
import { jsonpath, jsonpatch } from "json-p3";
const query = "$.users[?@.status == 'pending'].status";
const data = {
users: [
{ id: "usr_101", name: "Alice", status: "pending" },
{ id: "usr_102", name: "Bob", status: "active" },
{ id: "usr_103", name: "Charlie", status: "pending" },
],
};
const nodes = jsonpath.find(query, data);
const patchOps = nodes.map((node) => node.replaceOp("active"));
jsonpatch.apply(patchOps, data);
console.log(JSON.stringify(data, null, 2));
{
"users": [
{
"id": "usr_101",
"name": "Alice",
"status": "active"
},
{
"id": "usr_102",
"name": "Bob",
"status": "active"
},
{
"id": "usr_103",
"name": "Charlie",
"status": "active"
}
]
}