I have a JSON document where some values can be null. Using for expressions in json4s, how I can yield None, instead of nothing?
The following will fail to yield when the value for either of the fields FormattedID
or PlanEstimate
is null
.
val j: json4s.JValue = ...
for {
JObject(list) <- j
JField("FormattedID", JString(id)) <- list
JField("PlanEstimate", JDouble(points)) <- list
} yield (id, points)
For example:
import org.json4s._
import org.json4s.jackson.JsonMethods._
scala> parse("""{
| "FormattedID" : "the id",
| "PlanEstimate" : null
| }""")
res1: org.json4s.JValue = JObject(List((FormattedID,JString(the id)),
(PlanEstimate,JNull)))
scala> for {
| JObject(thing) <- res1
| JField("FormattedID", JString(id)) <- thing
| } yield id
res2: List[String] = List(the id)
scala> for {
| JObject(thing) <- res1
| JField("PlanEstimate", JDouble(points)) <- thing
| } yield points
res3: List[Double] = List()
// Ideally res3 should be List[Option[Double]] = List(None)
According to the documentation,
Explaining why your for comprehension doesn't yield anything.
Of course, a
null
value is mapped toNone
internally.What about this
The last command should look like:
Or like