比较Scala中的json等式

Dan*_*ier 15 json scala equality equals

如何在scala中比较两个json结构是否相同?

例如,如果我有:

{
  resultCount: 1,
  results: [
    {
      artistId: 331764459,
      collectionId: 780609005
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

{
  results: [
    {
      collectionId: 780609005,
      artistId: 331764459
    }
  ],
  resultCount: 1
}
Run Code Online (Sandbox Code Playgroud)

他们应该被认为是平等的

Ami*_*ico 15

如果json库写得正确,你应该能够做到json1 == json2.这不适合你吗?

这是使用spray-json,虽然我希望每个json库都有相同的内容:

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
Run Code Online (Sandbox Code Playgroud)

Spray-json使用一个不可变的scala Map来表示抽象语法树中的一个JSON对象,这个对象是由解析产生的,所以它只是Map一个相等的语义才能使它工作.