raoulsson
raoulsson

Reputation: 16365

How to handle None values in JSON

I have some code that builds a JSON object in Scala in the Playframework context

def toJson(): JsObject = Json.obj(
  "status" -> JsString(result.getOrElse("fail")),
  "age" -> JsNumber(age.getOrElse(0))
)

Where result and age are wrapped in an Option. The getOrElse part in the age line indicates age is not available. That's what I would like to get around.

The resulting output is:

{
status: "fail",
age: 0
}

Question A: In the example, age is None so getOrElse returns a 0 which would have to be interpreted by the clients as some magic number with special meaning. I would like to return something like None but the play.api.libs.json.JsNumber expects a scala.BigDecimal.

Is there a way to get around this somehow?

Question B: A solution to Question A would be to leave out the age in case it is not available so the result looks like:

{
status: "fail"
}

I cannot mess around within the Json.obj(a, b, ...) construct...

So how would the code look like to achieve something like this?

Upvotes: 0

Views: 245

Answers (1)

cmbaxter
cmbaxter

Reputation: 35443

See if something like this works for you:

val fields:Seq[Option[(String,JsValueWrapper)]] = Seq(
  result.map(s => ("status", JsString(s))),
  age.map(i => ("age", JsNumber(new BigDecimal(i))))
)
val finalFields = fields.flatten

Json.obj(finalFields:_*)   

When the Seq gets flattened, the None types in it should be removed and thus will not be part of the resulting JsObject.

Upvotes: 2

Related Questions