Does circe
provide any function to check if an io.circe.Json
object is empty?
The Json documentation doesn't report anything about it, while the JsonObject documentation talks about an isEmpty function, but I verified that
{}.asJson.asObject.isEmpty // false
so it doesn't work as I expected.
It does not work in a way you expected, because Json.asObject
returns Some
in case if underlying JSON is object, because apart of that it also can either String
, Number
, Null
or Array
, hence "{}".asObject
(not really correct just for sake of example) - returns Some(JsonObject())
and you receive false
because Some.isEmpty=false
.
What you want is :
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`
Scastie: https://scastie.scala-lang.org/GgHGChNoRlGq0HxmSkf76Q