Compare two json array in c# and get only the difference in separate object

compare two json objects and get difference
c# compare two objects and get differences
compare two json objects and get difference java
c difference between two json files
compare two dynamic objects in c#
compare json objects javascript
json diff python
json diff command line

I am trying to compare two Json array and get only the changes or difference in the array. idea is to insert only the new records to the Database.

The belwo implementation based on the below links

https://www.experts-exchange.com/questions/29044077/Compare-to-json-string-in-c-and-get-results.html

https://code.i-harness.com/en/q/17b9432

using Newtonsoft.Json;

using Newtonsoft.Json.Linq;

string newData = string.Empty;
JObject newDataJObject = null;

string oldData = string.Empty;
JObject oldDataJObject = null;


 newData="{"RECORDS":[{"ENGINE":"JZMBVB23034","CHASSIS":"MD2DSJZZZVWB78384","PRODH":"DISCOVER","LANDX":"BANGLADESH","AUART":"ZVEX","WADAT_IST":null},{"ENGINE":"PFZWJL61018","CHASSIS":"","PRODH":"BOXER","LANDX":"EGYPT","AUART":"ZVKP","WADAT_IST":null},{"ENGINE":"JZMBVB23035","CHASSIS":"MD2DSJZZZVWB78384","PRODH":"DISCOVER","LANDX":"BANGLADESH","AUART":"ZVKP","WADAT_IST":null}]}"
 newDataJObject=JObject.Parse(newData);


 oldData="{"RECORDS":[{"ENGINE":"JZMB23034","CHASSIS":"MD2DSJZZVWB78384","PRODH":"DISCOVER","LANDX":"BANGLADESH","AUART":"ZVEX","WADAT_IST":null},{"ENGINE":"PFZW61018","CHASSIS":"","PRODH":"BOXER","LANDX":"EGYPT","AUART":"ZVKP","WADAT_IST":null}]}";
 oldDataJObject = JObject.Parse(oldData);




 bool result = JToken.DeepEquals(newDataJObject, oldDataJObject);

                    StringBuilder returnString = new StringBuilder();

                    returnString = CompareObjects(newDataJObject, oldDataJObject);

 private static StringBuilder CompareObjects(JObject source, JObject target)
        {
            StringBuilder returnString = new StringBuilder();
            foreach (KeyValuePair<string, JToken> sourcePair in source)
            {
                if (sourcePair.Value.Type == JTokenType.Object)
                {
                    if (target.GetValue(sourcePair.Key) == null)
                    {
                        returnString.Append("Key " + sourcePair.Key
                                            + " not found" + Environment.NewLine);
                    }
                    else if (target.GetValue(sourcePair.Key).Type != JTokenType.Object)
                    {
                        returnString.Append("Key " + sourcePair.Key
                                            + " is not an object in target" + Environment.NewLine);
                    }
                    else
                    {
                        returnString.Append(CompareObjects(sourcePair.Value.ToObject<JObject>(),
                            target.GetValue(sourcePair.Key).ToObject<JObject>()));
                    }
                }
                else if (sourcePair.Value.Type == JTokenType.Array)
                {
                    if (target.GetValue(sourcePair.Key) == null)
                    {
                        returnString.Append("Key " + sourcePair.Key
                                            + " not found" + Environment.NewLine);
                    }
                    else
                    {
                        returnString.Append(CompareArrays(sourcePair.Value.ToObject<JArray>(),
                            target.GetValue(sourcePair.Key).ToObject<JArray>(), sourcePair.Key));
                    }
                }
                else
                {
                    JToken expected = sourcePair.Value;
                    var actual = target.SelectToken(sourcePair.Key);
                    if (actual == null)
                    {
                        returnString.Append("Key " + sourcePair.Key
                                            + " not found" + Environment.NewLine);
                    }
                    else
                    {
                        if (!JToken.DeepEquals(expected, actual))
                        {
                            // todo:logic to get the difference here only

                            returnString.Append("Key " + sourcePair.Key + ": "
                                                + sourcePair.Value + " !=  "
                                                + target.Property(sourcePair.Key).Value
                                                + Environment.NewLine);
                        }
                    }
                }
            }
            return returnString;
        }
        private static StringBuilder CompareArrays(JArray source, JArray target, string arrayName = "")
        {
            var returnString = new StringBuilder();
            for (var index = 0; index < source.Count; index++)
            {

                var expected = source[index];
                if (expected.Type == JTokenType.Object)
                {
                    var actual = (index >= target.Count) ? new JObject() : target[index];
                    returnString.Append(CompareObjects(expected.ToObject<JObject>(),
                        actual.ToObject<JObject>()));
                }
                else
                {

                    var actual = (index >= target.Count) ? "" : target[index];
                    if (!JToken.DeepEquals(expected, actual))
                    {
                        if (String.IsNullOrEmpty(arrayName))
                        {
                            returnString.Append("Index " + index + ": " + expected
                                                + " != " + actual + Environment.NewLine);
                        }
                        else
                        {
                            returnString.Append("Key " + arrayName
                                                + "[" + index + "]: " + expected
                                                + " != " + actual + Environment.NewLine);
                        }
                    }
                }
            }
            return returnString;
        }

now the expected result what i want is to get only the changes in the array object like this ie

   {
        "ENGINE": "JZMBVB23035",
        "CHASSIS": "MD2DSJZZZVWB78384",
        "PRODH": "DISCOVER",
        "LANDX": "Bangladesh",
        "AUART": "ZVKP"
    }

Any help will be appreciated.

Thanks

Dev

You can deserialize both Json and then compare the lists. For example,

public class RECORD
{
    public string ENGINE { get; set; }
    public string CHASSIS { get; set; }
    public string PRODH { get; set; }
    public string LANDX { get; set; }
    public string AUART { get; set; }
    public object WADAT_IST { get; set; }
}

public class RootObject
{
    public List<RECORD> RECORDS { get; set; }
}

using the above data structure, we can deserialize as follows.

var newDataList = JsonConvert.DeserializeObject<RootObject>(newData);
var oldDataList = JsonConvert.DeserializeObject<RootObject>(oldData);

Now we can find the difference as follows

var result = newDataList.RECORDS.Except(oldDataList.RECORDS)

Find and return JSON differences using newtonsoft in C#?, But now c s have different values. So they are also There's a nice json diff tool I came across. It works flawlessly for Arrays and Objects can be nested inside each other. UPDATE: It only tells you about differences from the point of view of the source list. If a key <summary> /// Deep compare two NewtonSoft JObjects. There might be some modules where you need to track two JSON objects and return only a part of the JSON with the keys whose values are different. For example, consider two JSON strings as: 1. 2. 3. var a =' {"1":"Good","2":"Team","3": [Good,Team],"4": [Plays,Well]}'; var b =' {"1":"Better","2":"Team","3": [Better,Team],"4": [Plays,Well],"5":"abc"}';

with the help of above post and used InitializationKeysComparer class. then it works like charm

List<RECORDS> dataToInsert = objNewData.Except(objOldData, new InitializationKeysComparer()).ToList();

    public class InitializationKeysComparer : IEqualityComparer<RECORDS>
    {
        public bool Equals(RECORDS x, RECORDS y)
        {
            return (x.ENGINE.Trim().Equals(y.ENGINE.Trim()) && x.PRODH.Trim().Equals(y.PRODH.Trim())&& x.LANDX.Trim().Equals(y.LANDX.Trim()));
        }

        public int GetHashCode(RECORDS obj)
        {
            return 0;
        }
    }

Deep diff between two object, using lodash · GitHub, @return {Object} Return a new object who represent the diff. */ @denis-shostik no, it does work properly, [1,2] and [2,1] are two different arrays. As the _.​transform method is iterating only over object (and thus unable to spot We use it in Kourou to spot differences between large JSON based config files for Kuzzle. Validate, format, and compare two JSON documents. See the differences between the objects instead of just the new lines and mixed up properties. Created by Zack Grossbart. Get the source code. Big thanks owed to the team behind JSONLint.

Probably this is what you want, isn't it?

var newData = @"{""RECORDS"":[{""ENGINE"":""JZMBVB23034"",""CHASSIS"":""MD2DSJZZZVWB78384"",""PRODH"":""DISCOVER"",""LANDX"":""BANGLADESH"",""AUART"":""ZVEX"",""WADAT_IST"":null},{""ENGINE"":""PFZWJL61018"",""CHASSIS"":"""",""PRODH"":""BOXER"",""LANDX"":""EGYPT"",""AUART"":""ZVKP"",""WADAT_IST"":null},{""ENGINE"":""JZMBVB23035"",""CHASSIS"":""MD2DSJZZZVWB78384"",""PRODH"":""DISCOVER"",""LANDX"":""BANGLADESH"",""AUART"":""ZVKP"",""WADAT_IST"":null}]}";
var oldData = @"{""RECORDS"":[{""ENGINE"":""JZMB23034"",""CHASSIS"":""MD2DSJZZVWB78384"",""PRODH"":""DISCOVER"",""LANDX"":""BANGLADESH"",""AUART"":""ZVEX"",""WADAT_IST"":null},{""ENGINE"":""PFZW61018"",""CHASSIS"":"""",""PRODH"":""BOXER"",""LANDX"":""EGYPT"",""AUART"":""ZVKP"",""WADAT_IST"":null}]}";

var newDataJObject = JObject.Parse(newData);
var oldDataJObject = JObject.Parse(oldData);

var diff = JsonDiffer.JsonDifferentiator.Differentiate(oldDataJObject, newDataJObject);

Result

{
   "*RECORDS": [
      {
         "*ENGINE": "JZMB23034",
         "*CHASSIS": "MD2DSJZZVWB78384"
      },
      {
         "*ENGINE": "PFZW61018"
      },
      {
         "+ENGINE": "JZMBVB23035",
         "+CHASSIS": "MD2DSJZZZVWB78384",
         "+PRODH": "DISCOVER",
         "+LANDX": "BANGLADESH",
         "+AUART": "ZVKP",
         "+WADAT_IST": null
      }
   ]
}

https://www.nuget.org/packages/JsonDiffer

Compare 2 objects, Is there an easy way to compare the contents of objects between 2 different databases? C. Both the objects have email address and I want only those email address Validate, format, and compare two JSON documents. 5 Jul 2019 Objects are not like arrays or strings. log) Step 2 - Add the static class CompareObject. You can deserialize both Json and then compare the lists. For example, public class RECORD { public string ENGINE { get; set; } public string CHASSIS { get; set; } public string PRODH { get; set; } public string LANDX { get; set; } public string AUART { get; set; } public object WADAT_IST { get; set; } } public class RootObject { public List<RECORD> RECORDS { get; set; } }

How to compare 2 json files having same key-values but in different , For sorting JSONs: Read the file and deserialize using GSON and get it as a How do I compare 2 json files having same key-values but in different order in java? de-serializer, convert the 2 JSON files into two Student/Employee objects​. 5. How do I remove a few fields from the JSON array response using JavaScript? Given two JavaScript array/array objects and the task is to compare the equality of both array objects. Approach 1: Use jQuery not () method to check for each element of array1, if it is not present in array2 or for each element of array2, if this is not present in array1, then it return false in both cases. Also check the length of both arrays.

How to compare two JSON objects with their key-value pairs using , If you've a JSON format set, like a particular API endpoint returning JSON, How can I compare two JSON objects with their key-value pairs using There are actually a couple of ways to do this, and it depends on the type of data you have. Should I use a table that has only one column, or instead use a JSON file that  JSON array vs JSON Object could be simply termed as list vs key-value pair. JSON array in collection of order values with [], while JSON object is collection of unordered key, value pair woth curly braces { }.

Merge two json objects with same key, In this tutorial, we learned how to create simple JSON Objects using a C# only allowed for arrays I have been using this code which modifies the json object in place. 1 How to compare JSON values, objects and arrays (JSON Compare) June 4, two objects with the same number of undefined keys, but with different​  If the reference object and the difference object are the same, there's no output, unless you use the IncludeEqual parameter. PSCustomObject. If the objects are different, Compare-Object wraps the differing objects in a PSCustomObject wrapper with a SideIndicator property to reference the differences.

Comments
  • Turn them into normal arrays and then just find the difference. Trying to deal with it using jObjects is just making it more complicated than it needs to be.
  • thanks for your reply. i tried the same var newDataList = JsonConvert.DeserializeObject<RootObject>(newData); var oldDataList = JsonConvert.DeserializeObject<RootObject>(oldData); var emo = newDataList.RECORDS.Except(oldDataList.RECORDS).ToList(); but emo is giving all the records(count 3) not filtering.
  • @Devanathan.S Wouldn't that be the expected output as well ? since the all records has changed when compared to old. For example, in the first record Engine has changed from "JZMB23034" to "JZMBVB23034". Similarly in others.