使用 Circe 检查 JSON 是否为空

Check if a JSON is empty using Circe

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

Json documentation doesn't report anything about it, while the JsonObject documentation talks about an isEmpty函数,但我验证了

 {}.asJson.asObject.isEmpty // false

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

我只是忘记了 asObject returns 和 Option[JsonObject],所以 isEmpty 只是检查它是 Some

.asObject.map(_.isEmpty).getOrElse(true)

有效

它没有按您预期的方式工作,因为 Json.asObject returns Some 如果基础 JSON 是对象,因为除此之外它还可以StringNumberNullArray,因此 "{}".asObject(不正确只是为了举例)- returns Some(JsonObject()) 并且您收到 false 因为 Some.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`

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