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.
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.
Note: The json
s 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.
Comparing Json: Comparing json is quite simple, we can use '==' operator, Note: '==' and 'is' operator are not same, '==' operator is use to check equality of values , whereas 'is' operator is used to check reference equality, hence one should use '==' operator, 'is' operator will not give expected result.
Solution 1 Your first code step would be to convert the JSON string to an object, using JSON. parse . Then you can use Object. keys to get all keys from the first object, and you can loop over these keys to see the difference in values in the two objects.
var json2 = @"{ ""name"": ""Tod"" }" ; Followed by that, we will call the Diff method on our JsonDiffPatch object. As input, we will pass both JSON strings and as output we will get another JSON string, representing the diff. Note that the order of the JSON parameters influence the order of the diff in the result.
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).
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:
The ordering of A should be respected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With