Skip to content

lukascivil/json-difference

Repository files navigation

JsonDifference

Total Downloads npm version CI Node.js Package Project Status: Active – The project has reached a stable, usable state and is being actively developed. codecov MIT License

Computes the difference between two objects and returns an intuitive result. No matter how big your JSON is, the diff will be returned pretty fast.

The question you should ask is: Given my old structure what was changed, removed or added to the new structure?

Live Demo

Master (deprecated link) Latest release (new)

Installation

yarn add json-difference

Or

<script type="module">
  import { getDiff } from 'https://rawgit.com/lukascivil/jsondiffer/master/dist.browser/json-difference.mjs'
</script>

Example

Running example:

yarn example {simple, stress}

Usage of getDiff()

Method:

getDiff(oldStruct, newStruct)

Returns the structural difference between oldStruct and newStruct.

Simple usage:

import { getDiff } from 'json-difference'

const coffee = { color: { color1: 'black', color2: 'brown' }, special: true }
const oil = { color: { color1: 'red', color2: 'blue' }, special2: false, especial3: [{}] }

// Get JsonDiff delta
const diff = getDiff(coffee, oil)
const diff2 = getDiff(coffee, oil, { isLodashLike: true })

console.log(diff)
console.log(diff2)

Output:

{
  "added": [
    ["special2", false],
    ["especial3", []],
    ["especial3/0[]", {}]
  ],
  "removed": [["special", true]],
  "edited": [
    ["color/color1", "black", "red"],
    ["color/color2", "brown", "blue"]
  ]
}
{
  "added": [
    ["special2", false],
    ["especial3", []],
    ["especial3[0]", {}]
  ],
  "removed": [["special", true]],
  "edited": [
    ["color.color1", "black", "red"],
    ["color.color2", "brown", "blue"]
  ]
}

Delta

The delta is an object that contains three properties that follow a pattern. This pattern will be shown below:

Operation Pattern
"edited" [path_to_the_key, old_value, new_value]
"added" [path_to_the_key, value]
"removed" [path_to_the_key, old_value]
value Explanation
"root" Indicates the root of the object
"@{}" Indicates that the key is a non-leaf node of type Object
"@[]" Indicates that the key is a non-leaf node of type Array

Some operations

JSON original JSON modified Delta
{} [] "edited": [ [ "root", {}, [] ] ]
[] {} "edited": [ [ "root", [], {} ] ]
[{}] [[]] "edited": [ [ "0[]", {}, [] ] ]
{"a": "b"} {"a": "c"} "edited": [ [ "a", "b", "c" ] ]
{"":""} {"": "a"} "edited": [ [ "", "", "a" ] ]
{"":{"":""}} {"": {"": "a"}} "edited": [ [ "/", "", "a" ] ]
[] [{}] "added": [ [ "0[]", {} ] ]
{} {"a":"b"} "added": [ [ "a", "b" ] ]
{"a":"b"} {} "removed": [ [ "a", "b" ] ]
[{}] [] "removed": [ [ "0[]", {} ] ]
[{"":""}] {"":""} "added": [ [ "", "" ] ], "removed": [ [ "0[]", {} ], [ "0[]/", "" ] ], "edited": [ [ "root", [], {} ] ]