简体   繁体   English

从两个对象生成JSON补丁

[英]Generate JSON-patch from two objects

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 ? 给定两个Javascript对象( AB ),有没有办法生成JSON补丁 ,这样当该补丁应用于A它会将对象的属性更改为对象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. 例如,给定假设的JSONPatch函数(可能是与下面链接的函数之一类似的函数),所需的是generate_patch函数。

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. 在这个问题中, AB是Javascript对象。 A patch created by RFC6902 is JSON that would indicate an array of operations which when applied to A that object would become B . RFC6902创建的补丁是JSON,它表示一个操作数组,当应用于A ,该对象将变为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. generate_patch函数不需要返回JSON,而是为了提高效率可以返回一个Javascript对象,当JSON.stringify被调用时,该对象成为RFC6902 JSON补丁文档。

The projects I have found on the topic are: 我在这个主题上找到的项目是:

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. 这段代码https://www.npmjs.org/package/rfc6902似乎是针对所述RFC的补丁和差异的完整javascript实现。

I haven't used it myself, but the documentation makes it look like what you asked for. 我自己没有使用它,但文档使它看起来像你要求的。

Since version 0.3.9, https://github.com/Starcounter-Jack/Fast-JSON-Patch has a compare method which returns a difference between 2 objects. 从版本0.3.9开始, https://github.com/Starcounter-Jack/Fast-JSON-Patch有一个compare方法,它返回2个对象之间的差异。 If I understand correctly, that may be what you were looking for 如果我理解正确,那可能就是你要找的东西

I have also written a library to generate patches: https://github.com/gregsexton/json-patch-gen 我还写了一个库来生成补丁: https//github.com/gregsexton/json-patch-gen

I found out about 'rfc6902' after having written and used json-patch-gen. 在编写并使用了json-patch-gen后,我发现了'rfc6902'。 I'm not sure how they compare: it may be worth trying out both to see if one fits your needs better. 我不确定他们如何比较:可能值得尝试两者,看看是否更符合您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM