我想比较2个JSON并在Scala中获得它们之间的所有差异。例如,我想比较一下:
{"a":"aa", "b": "bb", "c":"cc" }
和
{"c":"cc", "a":"aa", "d":"dd"}
我想获得b
和d
。
答案 0 :(得分:3)
如果不是限制,你可以使用http://json4s.org/它有一个很好的差异功能。
根据问题进行示例:
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
它将返回:
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))))
祝你好运
答案 1 :(得分:3)
最后,我使用JSONassert执行相同的操作。
例如,
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);
它返回
friends[id=3].pets[]: Expected bird, but not found ; friends[id=3].pets[]: Contains cat, but not expected