panza
panza

Reputation: 1431

How to check whether a JsValue is null or Empty [Scala, Play]

I am trying to write a simple utility to check whether a JsValue is null or empty. I have this:

def is_nullOrEmpty(x: JsValue): JsBoolean = {
  JsBoolean(
    (x) match {
      case _ => x == null
      case _ => x.toString().isEmpty  
    }
  )
}

I am fairly new to Scala + Play and I am not sure whether this is the correct way to go about.

Alternatively this:

def is_nullOrEmpty(x: JsValue) = x == null || x.toString().trim.isEmpty

Where I am also including .trim

Can you help?

Upvotes: 0

Views: 2361

Answers (2)

Tomer Shetah
Tomer Shetah

Reputation: 8529

You can use Option. Please try the following:

def is_nullOrEmpty(x: JsValue): JsBoolean = Option(x) match {
  case None =>
    JsFalse
  case Some(value) =>
    if (Json.stringify(value) == "") {
      JsFalse
    } else {
      JsTrue
    }
}

Or even easier in one liner:

def is_nullOrEmpty1(x: JsValue): JsBoolean = JsBoolean(Option(x).exists(Json.stringify(_) != ""))

Having said that, the check of an empty string is redundant, as elaborated at Why does JSON.parse fail with the empty string? and in many other posts.

Code run at Scastie.

Upvotes: 1

sarveshseri
sarveshseri

Reputation: 13985

I don't understand - why is the output of a method named as is_nullOrEmpty is JsBoolean ? Did you mean Boolean ?

def isNullOrEmpty(x: JsValue): Boolean = x match {
  case null => true
  case JsNull => true
  case _ => false
}

In case you also want to check the emptiness of String or Array for your JsValue then,

def isNullOrEmpty(x: JsValue): Boolean = x match {
  case null => true
  case JsNull => true
  case JsString(string) => string.trim.isEmpty
  case JsArray(array) => array.isEmpty
  case _ => false
}

Or, if you wanted to convert it to JsBoolean and return null if it is not a compatible value,

def convertToJsBoolean(x: JsValue): JsBoolean = x match {
  case jsBoolean: JsBoolean => jsBoolean
  case _ => null
}

In this case, you can also use Option[JsBoolean] as your output type,

def convertToJsBoolean(x: JsValue): Option[JsBoolean] = x match {
  case jsBoolean: JsBoolean => Option(jsBoolean)
  case _ => None
}

Upvotes: 2

Related Questions