比较Scala中的JSON相等性 [英] Compare json equality in Scala

查看:125
本文介绍了比较Scala中的JSON相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I compare if two json structures are the same in scala?

例如,如果我有:

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

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

被认为是相等的

推荐答案

应该应该能够简单地执行 json1 = = json2 ,如果json库编写正确。

You should be able to simply do json1 == json2, if the json libraries are written correctly. Is that not working for you?

这是 spray-json ,尽管我希望每个json库都可以做到这一点:

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使用不可变的scala Map 表示解析后的抽象语法树中的JSON对象,因此它只是 Map 的相等语义可以做到这一点。

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.

这篇关于比较Scala中的JSON相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆