Generate JSON-patch from two objects

Brian M. Hunt picture Brian M. Hunt · Mar 21, 2014 · Viewed 10.1k times · Source

Given two Javascript objects (A and B), is there a way to generate the JSON patch, so that when that patch is applied to A it would change the object's properties to that of object B?

For example, given hypothetical JSONPatch function (perhaps being a function of similar name to one of those linked below), what is desired is the generate_patch function.

patch = generate_patch(A, B) JSONPatch.apply(patch, A) # modifies A so that it has the same properties as B.

In this question A and B are Javascript objects. A patch created by RFC6902 is JSON that would indicate an array of operations which when applied to A that object would become B. The generate_patch function need not return JSON though, rather for efficiency could return a Javascript object that becomes the RFC6902 JSON-patch document when JSON.stringify is called on it.

The projects I have found on the topic are:

Answer

jfriend00 picture jfriend00 · Mar 21, 2014

Turning my comment into an answer...

This code https://www.npmjs.org/package/rfc6902 seems to be a full javascript implementation of both patch and diff for the stated RFC.

I haven't used it myself, but the documentation makes it look like what you asked for.