Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two json are equivalent

Tags:

json

c#

I've two json files. They should be the same regardless formatting and ordering of elements.

For example these two jsons are equivalent because attributes and arrays are the same, only their order and the formatting type are different:

{
  "type" : "integer",
  "values": [
    {
      "value": 1
    },
    {
      "value": 2
    }
  ]
}

and

{
  "values": [
    { "value": 1 }, { "value": 2 }
  ],
  "type" : "integer"
}

If I store them into two separate strings and I compare them, obviously the comparison will say that they are different. Instead I want to check if they are equals from a semantic point of view, and they are because they have the same attributes, and respective arrays are the same.

Is there a way in C# to check that these two json are equivalent, if I store them in two separate strings?

like image 630
Jepessen Avatar asked Apr 16 '17 21:04

Jepessen


People also ask

How can we compare two JSON files?

You can also directly compare two JSON files by specifying their urls in the GET parameters url1 and url2. Then you can visualize the differences between the two JSON documents. It highlights the elements which are different: Different value between the two JSON: highlight in red color.

Can we compare two JSON objects?

Similarly, we can also compare two JSON objects that contain a list element. It's important to know that two list elements are only compared as equal if they have the same values in the exact same order.


2 Answers

Using Newtonsoft.Json nuget package's DeepEquals :

using Newtonsoft.Json.Linq;

var jsonText1 = File.ReadAllText(fileName1);
var jsonText2 = File.ReadAllText(fileName2);

var json1 = JObject.Parse(jsonText1);
var json2 = JObject.Parse(jsonText2);

var areEqual = JToken.DeepEquals(json1, json2);
like image 168
Emond Avatar answered Oct 02 '22 15:10

Emond


The best bet to do this is by using the "Newtonsoft.json"

Refer the below post :

Find differences between two json objects

like image 36
Mohit Gautam Avatar answered Oct 02 '22 16:10

Mohit Gautam