[英]Best way of returning differences of two json files programatically
I have two json files and I would like to get a json containing the differences. 我有两个json文件,我想得到一个包含差异的json。 It is important that only the actual differences of content should be shown, regardless of changing the order of some elements.
重要的是,无论是否改变某些元素的顺序, 都只应显示内容的实际差异。
What would be the best way to do that? 最好的方法是什么? I am searching for a solution as efficient as possible, since
json
s may contain lots of data, and users need jobs to be done as quick as possible. 我正在寻找尽可能高效的解决方案,因为
json
可能包含大量数据,用户需要尽快完成工作。
Note: The json
s might contain data encoded at different depths. 注意:
json
可能包含在不同深度编码的数据。 Any programming language is ok, but I would prefer an answer that could easily be implemented in php. 任何编程语言都可以,但我更喜欢一个可以在php中轻松实现的答案。
尝试使用array_diff函数
array_diff(json_decode($jsonData1), json_decode($jsonData2));
Basically, what you want is something similar to array_diff_assoc
, but applied to json objects, and recursive. 基本上,你想要的是类似于
array_diff_assoc
,但是应用于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. 由于引用问题,
array_diff
函数不是递归的:可以将数组的引用分配给该数组的条目,从而使数组无限递归。 I don't think it is possible to get the same situation with a json object, thus making a recursive function safe. 我不认为有可能与json对象获得相同的情况,从而使递归函数安全。
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: 假设您希望计算对象A和B之间的差异,并将结果放在对象C中。原则是循环
foreach
A的每个字段( foreach
应该这样做),以及何时:
The ordering of A should be respected. A的顺序应该得到尊重。
For this task you can try with https://github.com/swaggest/json-diff 对于此任务,您可以尝试使用https://github.com/swaggest/json-diff
It will do key-wise recursive comparison (order of keys does not matter) and produce JSON Patch (specified in RFC 6902 from the IETF). 它将进行按键式递归比较(键的顺序无关紧要)并生成JSON补丁 (在IETF的RFC 6902中指定)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.