Search code examples
jsonscalaplayframework

In Play 2 how to check if a JsValue variable is NULL?


This question may smell stupid but I really want to know how to check a NULL JsValue in Play 2:

scala> import play.api.libs.json._
import play.api.libs.json._

scala> val json = Json.obj("a" -> true)
json: play.api.libs.json.JsObject = {"a":true}

scala> val a = json \ "nonExisting"
a: play.api.libs.json.JsValue = null

scala> a == null
res1: Boolean = false

scala> Option(a)
res2: Option[play.api.libs.json.JsValue] = Some(null)

You can see the value of the variable a is null but the == check returns with false. However the below works as expected:

scala> val b: JsValue = null
b: play.api.libs.json.JsValue = null

scala> b == null
res3: Boolean = true

And when I turned to type conversion with asOpt, it seems work again:

scala> val c = json \ "a"
c: play.api.libs.json.JsValue = true

scala> c.asOpt[Boolean]
res4: Option[Boolean] = Some(true)

scala> a.asOpt[Boolean]
res5: Option[Boolean] = None

Solution

  • If you tried the same operation in JavaScript with actual JSON, normally you'd get undefined not null. This is represented by JsUndefined not JsNull. You can look for this instead:

    a.isInstanceOf[JsUndefined]
    

    or through using pattern matching:

    a match { case _: JsUndefined => true; case _ => false })
    

    How cool is that Scala's strong typing, accurately reflecting the JSON behaviour!? :)