Daniel Cukier Daniel Cukier - 1 year ago 175
Scala Question

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


results: [
collectionId: 780609005,
artistId: 331764459
resultCount: 1

They should be considered equal

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download