A dependency-free runtime TypeScript library for comparing JSON values and finding value locations in formatted JSON text.
npm install json-compassimport { compareJson } from "json-compass";
const result = compareJson(
{ user: { name: "Ada", active: true } },
{ user: { name: "Grace", active: true } },
);Result:
{
"equal": false,
"changes": [
{
"type": "changed",
"path": "/user/name",
"oldValue": "Ada",
"newValue": "Grace"
}
]
}Changes use RFC 6901 JSON Pointer paths and report added, removed, and changed values. Arrays are compared by index.
npx json-compass original.json updated.json
npx json-compass --json original.json updated.jsonWhen installed globally, the command is available as json-compare:
npm install --global json-compass
json-compare original.json updated.jsonExit codes:
0: Documents are equal.1: Differences were found.2: Invalid arguments, unreadable files, or invalid JSON.
import { findJsonLocation } from "json-compass";
const source = `{
"users": [
{
"name": "Ada"
}
]
}`;
findJsonLocation(source, ["users", 0, "name"]);
// { line: 4, column: 15 }Line and column numbers are 1-based and point to the start of the matched JSON
value. Array indexes may be numbers or numeric strings. A missing path returns
null, and invalid JSON throws a SyntaxError.
import { findJsonPath } from "json-compass";
const offset = source.indexOf('"Ada"') + 2;
findJsonPath(source, offset);
// ["users", 0, "name"]
findJsonPath(source, { line: 4, column: 16 });
// ["users", 0, "name"]Offsets are zero-based UTF-16 positions, matching JavaScript string indexes and
editor APIs such as CodeMirror. Alternatively, pass the same one-based
{ line, column } shape returned by findJsonLocation. The function returns
the deepest JSON path at that position, ready to pass back to
findJsonLocation. Invalid positions return null, and invalid JSON throws a
SyntaxError.
npm install
npm test
npm run check