Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 579
XuChu LIU Avatar asked Jun 26 '15 03:06

XuChu LIU


2 Answers

Check for equality with play.api.libs.json.JsNull:

if (a == JsNull) { ... }

or

a match {
  case JsNull => ...
}
like image 55
Rado Buransky Avatar answered Oct 27 '22 01:10

Rado Buransky


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!? :)

like image 38
bjfletcher Avatar answered Oct 27 '22 00:10

bjfletcher