以编程方式返回两个json文件之间的差异的最佳方法 [英] Best way of returning differences of two json files programatically

查看:156
本文介绍了以编程方式返回两个json文件之间的差异的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个json文件,我想获取一个包含差异的json. 很重要,无论更改某些元素的顺序如何,都只显示内容的实际差异.

I have two json files and I would like to get a json containing the differences. It is important that only the actual differences of content should be shown, regardless of changing the order of some elements.

做到这一点的最佳方法是什么?我正在寻找一种尽可能高效的解决方案,因为json可能包含大量数据,并且用户需要尽快完成工作.

What would be the best way to do that? I am searching for a solution as efficient as possible, since jsons may contain lots of data, and users need jobs to be done as quick as possible.

注意:json可能包含以不同深度编码的数据.任何编程语言都可以,但是我希望可以在php中轻松实现的答案.

Note: The jsons might contain data encoded at different depths. Any programming language is ok, but I would prefer an answer that could easily be implemented in php.

推荐答案

基本上,您想要的是与array_diff_assoc类似的东西,但适用于json对象,并且是递归的.

Basically, what you want is something similar to array_diff_assoc, but applied to json objects, and recursive.

由于引用问题,array_diff函数不是递归的:可以将数组的引用分配给该数组的条目,从而使数组无限递归.我认为使用json对象无法获得相同的情况,从而使递归函数变得安全.

The array_diff functions are not recursive because of reference issues: it is possible to assign a reference of an array to an entry of that array, making the array infinitely recursive. I don't think it is possible to get the same situation with a json object, thus making a recursive function safe.

让我们假设您希望计算对象A和对象B之间的差,并将结果保存在对象C中. 原理是遍历A的每个字段(foreach应该这样做),以及何时:

Let's suppose that you wish to compute the difference between object A and B, and have the result in object C. The principle is to loop over each field of A (a foreach should do), and when:

  • B中没有这样的字段,请通过C复制它.
  • B中存在一个相似的字段,将A字段与B字段之差的结果放入C中,这是对以这些字段为参数的diff函数以及结果的新鲜对象的递归调用.

应遵守A的顺序.

这篇关于以编程方式返回两个json文件之间的差异的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆