25

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:

Community
  • 1
  • 1
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343
  • How does this differ from simply cloning object B? –  Mar 21 '14 at 00:12
  • 1
    Are you literally talking about JSON (e.g. a text string) or are you talking about turning one Javascript object into another. Remember, JSON is a text format that can be parsed into an object. So, I'm trying to figure out if you're trying to change one JSON string into the other or if you're trying to change one Javascript object into the other. – jfriend00 Mar 21 '14 at 00:18
  • @MikeW - The patch is smaller and a string, suitable for the HTTP PATCH method, per RFC6902 – Brian M. Hunt Mar 21 '14 at 00:26
  • Yeah, that helps a lot. You should put that into your question. – jfriend00 Mar 21 '14 at 00:55
  • 1
    Start here perhaps: https://www.npmjs.org/package/rfc6902 – jfriend00 Mar 21 '14 at 00:57
  • @jfriend00 Comment added to question - good call. Great link - checking it out. – Brian M. Hunt Mar 21 '14 at 01:09

3 Answers3

12

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
10

Since version 0.3.9, https://github.com/Starcounter-Jack/Fast-JSON-Patch has a compare method which returns a difference between 2 objects. If I understand correctly, that may be what you were looking for

warpech
  • 6,293
  • 4
  • 35
  • 36
3

I have also written a library to generate patches: https://github.com/gregsexton/json-patch-gen

I found out about 'rfc6902' after having written and used json-patch-gen. I'm not sure how they compare: it may be worth trying out both to see if one fits your needs better.

Greg Sexton
  • 9,189
  • 7
  • 31
  • 37