Reputation: 163
I want to compare 2 JSON and get all the differences between them in Scala. For example, I would like to compare:
{"a":"aa", "b": "bb", "c":"cc" }
and
{"c":"cc", "a":"aa", "d":"dd"}
I'd like to get b
and d
.
Upvotes: 2
Views: 2913
Reputation: 163
Finally, I used JSONassert that does the same thing.
For example,
String expected = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"bird\",\"fish\"]}],pets:[]}";
String actual = "{id:1,name:\"Joe\",friends:[{id:2,name:\"Pat\",pets:[\"dog\"]},{id:3,name:\"Sue\",pets:[\"cat\",\"fish\"]}],pets:[]}"
JSONAssert.assertEquals(expected, actual, false);
it returns
friends[id=3].pets[]: Expected bird, but not found ; friends[id=3].pets[]: Contains cat, but not expected
source: http://jsonassert.skyscreamer.org/
Upvotes: 4
Reputation: 83
If it isn't a restriction you can use http://json4s.org/ it has a nice diff feature.
Follow an example based on question:
import org.json4s._
import org.json4s.native.JsonMethods._
val json1 = parse("""{"a":"aa", "b":"bb", "c":"cc"}""")
val json2 = parse("""{"c":"cc", "a":"aa", "d":"dd"}""")
val Diff(changed, added, deleted) = json1 diff json2
It will return:
changed: org.json4s.JsonAST.JValue = JNothing
added: org.json4s.JsonAST.JValue = JObject(List((d,JString(dd))))
deleted: org.json4s.JsonAST.JValue = JObject(List((b,JString(bb))))
Best regards
Upvotes: 6