Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare json equality in Scala

How can I compare if two json structures are the same in scala?

For example, if I have:

{
  resultCount: 1,
  results: [
    {
      artistId: 331764459,
      collectionId: 780609005
    }
  ]
}

and

{
  results: [
    {
      collectionId: 780609005,
      artistId: 331764459
    }
  ],
  resultCount: 1
}

They should be considered equal

like image 382
Daniel Cukier Avatar asked Apr 19 '14 22:04

Daniel Cukier


People also ask

How do you know if two JSON objects are equal?

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.

How to compare 2 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.

How to compare two JsonNode?

That's good enough to use JsonNode. equals: Equality for node objects is defined as full (deep) value equality. This means that it is possible to compare complete JSON trees for equality by comparing equality of root nodes.

How to compare two Jsons Java?

Compare JSON Objects with Custom Comparator The JsonNode. equals() method works fine for most of the cases in comparing two objects. However, Jackson provides one more variant of the equals() method, i.e., JsonNode. equals(comparator, JsonNode) for configuring the custom Java Comparator object.


Video Answer


1 Answers

You should be able to simply do json1 == json2, if the json libraries are written correctly. Is that not working for you?

This is with spray-json, although I would expect the same from every json library:

import spray.json._
import DefaultJsonProtocol._
Welcome to Scala version 2.10.4 (OpenJDK 64-Bit Server VM, Java 1.7.0_51).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val json1 = """{ "a": 1, "b": [ { "c":2, "d":3 } ] }""".parseJson
json1: spray.json.JsValue = {"a":1,"b":[{"c":2,"d":3}]}

scala> val json2 = """{ "b": [ { "d":3, "c":2 } ], "a": 1 }""".parseJson
json2: spray.json.JsValue = {"b":[{"d":3,"c":2}],"a":1}

scala> json1 == json2
res1: Boolean = true

Spray-json uses an immutable scala Map to represent a JSON object in the abstract syntax tree resulting from a parse, so it is just Map's equality semantics that make this work.

like image 197
AmigoNico Avatar answered Oct 05 '22 14:10

AmigoNico