Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate JSON-patch from two objects

Tags:

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:

  • https://github.com/bruth/jsonpatch-js - only patches (does not generate a patch)
  • http://jsonpatchjs.com/ - same
  • https://github.com/Starcounter-Jack/Fast-JSON-Patch - observes an object, does not take two different objects
like image 272
Brian M. Hunt Avatar asked Mar 21 '14 00:03

Brian M. Hunt


People also ask

What is JSON merge patch?

A JSON merge patch document describes changes to be made to a target JSON document using a syntax that closely mimics the document being modified.

What RFC 6902?

RFC 6902: JavaScript Object Notation (JSON) Patch.

When to use JSON Patch?

JSON Patch is a format for describing changes to a JSON document. It can be used to avoid sending a whole document when only a part has changed. When used in combination with the HTTP PATCH method, it allows partial updates for HTTP APIs in a standards compliant way. The patch documents are themselves JSON documents.


2 Answers

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.

like image 170
jfriend00 Avatar answered Sep 22 '22 00:09

jfriend00


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

like image 40
warpech Avatar answered Sep 20 '22 00:09

warpech