Skip to content
This repository has been archived by the owner on Mar 6, 2018. It is now read-only.

JSON8/merge-patch

Repository files navigation

IMPORTANT

This package moved to a monorepo. https://github.com/sonnyp/JSON8/tree/master/packages/merge-patch


JSON8 Merge Patch

build status

Introduction

JSON Merge Patch RFC 7396 implementation for JavaScript.

See also


Getting started

npm install json8-merge-patch


var ooMergePatch = require('json8-merge-patch');

or

<script src="node_modules/json8-merge-patch/JSON8MergePatch.js"></script>
var ooMergePatch = window.JSON8MergePatch

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 validness, use JSON8 valid.
doc = ooMergePatch.apply(doc, mergePatch);
var person = {
  "name": "John Doe",
  "friendly": true,
  "age": 18,
  "address": {
    "country": "France"
  }
}

var mergePatch = {
  "age": 19,
  "friendly": "maybe"
  "address": {
    "country": null
  }
}

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

patch

Alias for apply method.

diff

Compares two JSON documents and returns a JSON Merge Patch diff.

var a = {"foo": "bar", "bar": "foo"}
var b = {"foo": "foo"}

ooMergePatch.diff(a, b)
//{
//  "foo": "foo",
//  "bar": null
// }

toJSONPatch

JSON Patch is a more capable alternative to JSON Merge Patch. To work with JSON Patch see JSON8 Patch.

This method converts a JSON Merge Patch to a JSON Patch and is only available if the optional dependency JSON8 Pointer is available.

Does not validate the merge patch nor the patch for JSON validness, use JSON8 valid.

var JSONMergePatch = {
  "foo": {"bar": "foobar"},
  "bar": null}
}
var JSONPatch = ooMergePatch.toJSONPatch(JSONMergePatch)
//[
//  { op: 'add', path: '/foo/bar', value: 'foobar' },
//  { op: 'remove', path: '/bar' }
//]

Per specification a JSON Merge Patch that would successfully apply on a document might fail to apply once converted to a JSON Patch.

There are 3 cases:

Incompatible destination

var doc = []
var JSONMergePatch = {a: 'hello'}
var JSONPatch = toJSONPatch(JSONMergePatch)
// JSONPatch will fail to apply because doc is not an object

Wrong location

var doc = {}
var JSONMergePatch = {a: {b: 'hello'}}
var JSONPatch = toJSONPatch(JSONMergePatch)
// JSONPatch will fail to apply because doc.a doesn't exist

Remove non-existant value

var doc = {}
var JSONMergePatch = {a: null}
var JSONPatch = toJSONPatch(JSONMergePatch)
// JSONPatch will fail to apply because doc.a doesn't exist

I might add an option to the toJSONPatch method later to produce a successful JSON Patch but the only way to do this is to pass the document as well. Let me know if there is any interest or contribute.

Tests

npm install mocha browserify
npm test

Contributing

See CONTRIBUTING.md