Best way of returning differences of two json files programatically Best way of returning differences of two json files programatically json json

Best way of returning differences of two json files programatically


Try using array_diff function

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.

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.

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:

  • no such field exist in B, copy it over C.
  • a similar field exist in B, put in C the result of the difference of A field with B field, which is a recursive call on the diff function with those field as parameter, as well as a fresh object for the result.

The ordering of A should be respected.


For this task you can try with 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).