Compare json equality in Scala

2020-07-02 10:30发布

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
    }
  ]
}

and

{
  results: [
    {
      collectionId: 780609005,
      artistId: 331764459
    }
  ],
  resultCount: 1
}

They should be considered equal

4条回答
够拽才男人
2楼-- · 2020-07-02 10:53

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-07-02 10:59

Can confirm that it also works just fine with the Jackson library using == operator:

val simpleJson =
  """
    |{"field1":"value1","field2":"value2"}
  """.stripMargin

val simpleJsonNode = objectMapper.readTree(simpleJson)

val simpleJsonNodeFromString = objectMapper.readTree(simpleJsonNode.toString)

assert(simpleJsonNode == simpleJsonNodeFromString)
查看更多
Anthone
4楼-- · 2020-07-02 11:18

spray-json is definitely great, but I use Gson since I already had dependency on Gson library on my project. I am using these in my unit tests, works well for simple json.

import com.google.gson.{JsonParser}
import org.apache.flume.event.JSONEvent
import org.scalatest.FunSuite

class LogEnricherSpec extends FunSuite {
  test("compares json to json") {

    val parser = new JsonParser()

    assert(parser.parse("""
        {
          "eventType" : "TransferItems",
          "timeMillis" : "1234567890",
          "messageXml":{
            "TransferId" : 123456
          }
        } """.stripMargin)
      ==
      parser.parse("""
        {
          "timeMillis" : "1234567890",
          "eventType" : "TransferItems",
          "messageXml":{
            "TransferId" : 123456
          }
        }
      """.stripMargin))
}
查看更多
闹够了就滚
5楼-- · 2020-07-02 11:19

Calling the method compare_2Json(str1,str2) will return a boolean value. Please make sure that the two string parameters are json. Welcome to use and test.

      def compare_2Json(js1:String,js2:String): Boolean = {
        var js_str1 = js1
        var js_str2 = js2

        js_str1=js_str1.replaceAll(" ","")
        js_str2=js_str2.replaceAll(" ","")
        var issame = false
        val arrbuff1 = ArrayBuffer[String]()
        val arrbuff2 = ArrayBuffer[String]()
        if(js_str1.substring(0,1)=="{" && js_str2.substring(0,1)=="{" || js_str1.substring(0,1)=="["&&js_str2.substring(0,1)=="["){
          for(small_js1 <- split_JsonintoSmall(js_str1);small_js2 <- split_JsonintoSmall((js_str2))) {
            issame = compare_2Json(small_js1,small_js2)
            if(issame == true){
              js_str1 = js_str1.substring(0,js_str1.indexOf(small_js1))+js_str1.substring(js_str1.indexOf(small_js1)+small_js1.length)
              js_str2 = js_str2.substring(0,js_str2.indexOf(small_js2))+js_str2.substring(js_str2.indexOf(small_js2)+small_js2.length)
            }
          }
          js_str1 = js_str1.substring(1,js_str1.length-1)
          js_str2 = js_str2.substring(1,js_str2.length-1)

          for(str_js1 <- js_str1.split(","); str_js2 <- js_str2.split(",")){
            if(str_js1!="" && str_js2!="")
              if(str_js1 == str_js2){
                js_str1 = js_str1.substring(0,js_str1.indexOf(str_js1))+js_str1.substring(js_str1.indexOf(str_js1)+str_js1.length)
                js_str2 = js_str2.substring(0,js_str2.indexOf(str_js2))+js_str2.substring(js_str2.indexOf(str_js2)+str_js2.length)
              }
          }
          js_str1=js_str1.replace(",","")
          js_str2=js_str2.replace(",","")

          if(js_str1==""&&js_str2=="")return true
          else return false
        }
        else return false
      }

      def split_JsonintoSmall(js_str: String):ArrayBuffer[String]={
        val arrbuff = ArrayBuffer[String]()

        var json_str = js_str
        while(json_str.indexOf("{",1)>0 || json_str.indexOf("[",1)>0){
          if (json_str.indexOf("{", 1) < json_str.indexOf("[", 1) && json_str.indexOf("{",1)>0 || json_str.indexOf("{", 1) > json_str.indexOf("[", 1) && json_str.indexOf("[",1)<0 ) {
            val right = findrealm(1, json_str, '{', '}')
            arrbuff += json_str.substring(json_str.indexOf("{", 1), right + 1)
            json_str = json_str.substring(0,json_str.indexOf("{",1))+json_str.substring(right+1)
          }
          else {
            if(json_str.indexOf("[",1)>0) {
              val right = findrealm(1, json_str, '[', ']')
              arrbuff += json_str.substring(json_str.indexOf("[", 1), right + 1)
              json_str = json_str.substring(0, json_str.indexOf("[", 1)) + json_str.substring(right + 1)
            }
          }
        }
        arrbuff
      }

  def findrealm(begin_loc: Int, str: String, leftch: Char, rightch: Char): Int = {
    var left = str.indexOf(leftch, begin_loc)
    var right = str.indexOf(rightch, left)
    left = str.indexOf(leftch, left + 1)
    while (left < right && left > 0) {
      right = str.indexOf(rightch, right + 1)
      left = str.indexOf(leftch, left + 1)
    }
    right
  }
查看更多
登录 后发表回答