Best way of returning differences of two json files programatically

后端 未结 3 1709
悲哀的现实
悲哀的现实 2021-01-02 11:37

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

相关标签:
3条回答
  • 2021-01-02 11:53

    Try using array_diff function

    array_diff(json_decode($jsonData1), json_decode($jsonData2));
    
    0 讨论(0)
  • 2021-01-02 11:59

    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.

    0 讨论(0)
  • 2021-01-02 12:14

    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).

    0 讨论(0)
提交回复
热议问题