5

一部の値が null になる可能性がある JSON ドキュメントがあります。json4s の for 式を使用して、何も生成しない代わりに、どのように None を生成できますか?

フィールドFormattedIDまたはのいずれかの値が である場合、以下PlanEstimateは生成されませんnull

val j: json4s.JValue = ...
for {
  JObject(list) <- j
  JField("FormattedID", JString(id)) <- list
  JField("PlanEstimate", JDouble(points)) <- list
} yield (id, points)

例えば:

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)
4

4 に答える 4

1

ドキュメントによると、

任意の値を指定できます。値がない場合、フィールドと値は完全に削除されます。

scala> val json = ("name" -> "joe") ~ ("age" -> (None: Option[Int]))

スカラ > コンパクト (レンダリング (json))

res4: 文字列 = {"name":"joe"}

なぜあなたの理解が得られないのかを説明します。
もちろん、null値はNone内部的にマップされます。

于 2014-08-08T11:48:46.640 に答える
0

最後のコマンドは次のようになります。

for {
  JObject(thing) <- res1
} yield thing.collectFirst{case JField("PlanEstimate", JDouble(points)) => points}

またはのように

for {
  JObject(thing) <- res1
  points = thing.collectFirst{case JField("PlanEstimate", JDouble(p)) => p}
} yield points
于 2015-09-07T11:45:48.887 に答える
0

これはどうですか

 for {
      JObject(thing) <- res1      
      x = thing.find(_._1 == "PlanEstimate").flatMap(_._2.toOption.map(_.values))
     } yield x
于 2015-09-08T10:24:52.713 に答える