如何获得两个 JSON 之间的差异?
How to get differences between two JSONs?
我想比较 2 JSON 并在 Scala 中获得它们之间的所有差异。例如,我想比较:
{"a":"aa", "b": "bb", "c":"cc" }
和
{"c":"cc", "a":"aa", "d":"dd"}
我想要 b
和 d
。
如果没有限制,您可以使用 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
会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))))
此致
最后,我使用了 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);
它returns
friends[id=3].pets[]: Expected bird, but not found ; friends[id=3].pets[]: Contains cat, but not expected
我想比较 2 JSON 并在 Scala 中获得它们之间的所有差异。例如,我想比较:
{"a":"aa", "b": "bb", "c":"cc" }
和
{"c":"cc", "a":"aa", "d":"dd"}
我想要 b
和 d
。
如果没有限制,您可以使用 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
会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))))
此致
最后,我使用了 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);
它returns
friends[id=3].pets[]: Expected bird, but not found ; friends[id=3].pets[]: Contains cat, but not expected