jsonpatch.js

Overview

Download

Star the project on GitHub, or download it:

jsonpatch.js on GitHub jsonpatch.js v1.0.0-rc1

About jsonpatch.js

Example

mydoc = {
  "baz": "qux",
  "foo": "bar"
};
thepatch = [
  { "op": "replace", "path": "/baz", "value": "boo" }
]
patcheddoc = jsonpatch.apply_patch(mydoc, thepatch);
// patcheddoc now equals {"baz": "boo", "foo": "bar"}}

And that’s all you need for basic use, if the patch is invalid or won’t apply then you’ll get an error thrown. The original docucment is NOT mutated so you can use it for other things afterwards.

Where can jsonpatch.js be used?

You can use JSONPatch either in the browser or as a Node.js dependency. The tests will run in both environments.

To install JSONPatch as a Node.js dependency:

npm install jsonpatch

Testing jsonpatch.js

There are Mocha tests for JSONPatch in the test folder. To run the tests under Node.JS you must first install the test dependencies:

npm install mocha expect.js

(You should be able to install these at the same time as jsonpatch using the --dev flag to NPM, but at the time of writing this causes the Mocha install to fail, hopefully they’ll fix this soon!)

Once you have the test utilities installed you can run the tests with:

npm test jsonpatch

This will also run JSHint over the code, which picks up a lot of common JavaScript style problems.

To run the tests in the browser navigate to the test folder and open the runner.html file in your browser of choice.

Fixes and improvements

Send a pull request through GitHub or get in touch on Twitter (@almostobsolete) or email at tom@almostobsolete.net

History

Dharmafly is currently working to create a collaboration web app for NetDev that comprises a Node.js RESTful API on the back-end and an HTML5 Backbone.js application on the front. The JSON Patch library was created as an essential part of the RESTful API, and has been subsequently open sourced for the community with NetDev’s permission.

For further information about the API’s architecture, see Tom’s slides ”Hypermedia APIs and JavaScript Applications”, presented at Async in 2012.

The hole and the patch should be commensurate.
Thomas Jefferson