使用 Circe 检查 JSON 是否为空

mar*_*iii 0 json scala circe

是否circe提供任何函数来检查io.circe.Json对象是否为空?

Json文档没有报告任何相关内容,而JsonObject文档讨论了isEmpty函数,但我验证了这一点

 {}.asJson.asObject.isEmpty // false
Run Code Online (Sandbox Code Playgroud)

所以它没有像我预期的那样工作。

Iva*_*nko 5

它不会以您期望的方式工作,因为如果底层 JSON 是对象,则Json.asObject返回Some,因为除此之外它还可以String、或,因此(仅出于示例目的并不真正正确) - 返回并且您收到因为。你想要的是:NumberNullArray"{}".asObjectSome(JsonObject())falseSome.isEmpty=false

import io.circe._, io.circe.parser._
val emptyJsonObject = parse("{}").toOption.get //Unsafe operation for sake of answer example - DO NOT do it in production code.
println(emptyJsonObject.asObject) // prints `Some(object[])`
println(emptyJsonObject.asObject.exists(_.nonEmpty)) //prints `false`
Run Code Online (Sandbox Code Playgroud)

斯卡斯蒂: https: //scastie.scala-lang.org/GgHGChNoRlGq0HxmSkf76Q