json8-merge-patch

JSON Merge Patch toolkit for JavaScript

Usage no npm install needed!

<script type="module">
  import json8MergePatch from 'https://cdn.skypack.dev/json8-merge-patch';
</script>

README

JSON8 Merge Patch

Introduction

JSON Merge Patch RFC 7396 toolkit for JavaScript.


Getting started

npm install json8-merge-patch


const mergePatch = require("json8-merge-patch");

Methods

apply

Apply a JSON Merge Patch to a JSON document.

  • May mutates the target document, if you wish to pass a shallow copy use JSON8 clone.
  • Does not validate the patch nor the target nor the result for JSON correctness, use JSON8 valid.
doc = mergePatch.apply(doc, mergePatch);
let person = {
  "name": "John Doe",
  "friendly": true,
  "age": 18,
  "address": {
    "country": "France"
  }
}

const patch = {
  "age": 19,
  "friendly": "maybe"
  "address": {
    "country": null
  }
}

person = mergePatch.apply(person, patch)
/*
{
  "name": "John Doe",
  "friendly": "maybe",
  "age": 19,
  "address": {}
}
*/

object creation

When needed, apply creates objects with null prototype, you can choose the prototype to use with {proto: Object} as a third argument.

prototype pollution

apply will throw with an error if prototype pollution is attempted. You can allow for prototype pollution by passing {pollute: true} as a third argument.

patch

Alias for apply method.

diff

Compares two JSON documents and returns a JSON Merge Patch.

const a = { foo: "bar", bar: "foo" };
const b = { foo: "foo" };

mergePatch.diff(a, b);
/*
{
  "foo": "foo",
  "bar": null
}
*/