Let's say I have two JSON objects (obj1
and obj2
) which follow the same schema:
obj1:
{
"id": "94774",
"name": "testName",
"colour": "red",
"date": {
"year": 2021,
"month": 10,
"day": 21
}
}
obj2:
{
"id": "86970",
"name": "testName",
"foo": "bar",
"date": {
"year": 2022,
"month": 10,
"day": 21
}
}
I would like to compute the difference between these objects, and have the resulting changes presented in the same schema as the original objects (comments are added for clarity here, and not required in the resulting output):
{
"id": "86970", // modified
"colour": "", // removed
"foo": "bar", // added
"date": {
"year": 2022 // modified
}
}
How would this be done? I have tried using JsonPatchDocument from Microsoft, and that can provide me with the differences between two objects, but I can't get it in the output format I'd like.
I am using C# but would consider any other relevant solutions to this problem.
Edit:
How do you decide which of the two objects is the one to keep its values for building the difference json? - Steve
obj2
is the "newer" object, so the intent is that the elements in obj2
update the elements in obj1
.
Have you tried any of the nine answers from Find and return JSON differences using newtonsoft in C#?? E.g. this answer by Amin M shows a diff format that seems to resemble yours. - dbc
No I didn't think of searching StackOverflow before posting this question, thanks for the tip! /sarcasm. This is why people don't like this place. If any of those answers went any way to solving my problem then I wouldn't have posted the question, would I? Also thanks for the -1, super helpful and not toxic at all!