npm.io
1.16.3 • Published 4 months ago

json-difference

Licence
MIT
Version
1.16.3
Deps
0
Size
17 kB
Vulns
0
Weekly
0
Stars
58

json-difference

npm version Total Downloads MIT License

Computes the difference between two JSON structures and returns an intuitive path-based delta { added, removed, edited }. Fast even on large payloads.

Lightweight: 1.95 kB (gzip: 0.79 kB). Zero runtime dependencies.

Installation

yarn add json-difference
# or
npm install json-difference

Requirements: Node.js >=18.17.

Usage

import { getDiff } from 'json-difference'

const oldStruct = { color: { color1: 'black', color2: 'brown' }, special: true }
const newStruct = { color: { color1: 'red', color2: 'blue' }, special2: false }

getDiff(oldStruct, newStruct)
// {
//   added:   [["special2", false]],
//   removed: [["special", true]],
//   edited:  [
//     ["color/color1", "black", "red"],
//     ["color/color2", "brown", "blue"]
//   ]
// }
Lodash-style paths
getDiff(oldStruct, newStruct, { isLodashLike: true })
// edited: [["color.color1", "black", "red"], ...]

API

import {
  getDiff,
  getStructPaths,
  getEditedPaths,
  getPathsDiff,
  // types
  Delta,
  EditedPath,
  PathsDiff,
  StructPaths,
  JsonDiffOptions
} from 'json-difference'
getDiff(old, new, options?) => Delta

High-level entry point. Returns a full delta.

interface Delta {
  added:   Array<[path: string, value: unknown]>
  removed: Array<[path: string, value: unknown]>
  edited:  Array<[path: string, oldValue: unknown, newValue: unknown]>
}

Accepts objects, arrays, or JSON-encoded strings for both inputs.

getStructPaths(json, isLodashLike?) => StructPaths

Flattens a JSON into a plain object mapping dot/slash paths → leaf values. Building block used internally by getDiff.

getStructPaths({ a: { b: 1 }, c: [true] })
// { "a/b": 1, "c/0[]": true }
getEditedPaths(oldPaths, newPaths) => EditedPath[]

Given two flattened path maps, returns only the paths whose value changed.

getPathsDiff(pathsA, pathsB) => PathsDiff[]

Returns the paths present in pathsA but missing from pathsB (set difference). getDiff uses this with (old, new) for removed and with (new, old) for added.

Options

Option Type Default Description
isLodashLike boolean false Use lodash-style bracket notation (a.b[0]) instead of slash notation (a/b/0[])

Path format

Marker Meaning
__root__ Root object/array was replaced entirely
@{} Non-leaf node of type object
@[] Non-leaf node of type array
Reference operations
Original Modified Delta
{} [] edited: [["__root__", {}, []]]
{"a":"b"} {"a":"c"} edited: [["a", "b", "c"]]
{} {"a":"b"} added: [["a", "b"]]
{"a":"b"} {} removed: [["a", "b"]]
[{}] [] removed: [["0[]", {}]]

Browser usage (CDN)

<script type="module">
  import { getDiff } from 'https://json-difference.s3.amazonaws.com/1.16.1/json-difference-1.16.1.mjs'
  console.log(getDiff({ a: 1 }, { a: 2 }))
</script>

License

MIT lukascivil

Keywords