【问题标题】:argonaut - separating failures and successes when extracting List[A]argonaut - 提取 List[A] 时分离失败和成功
【发布时间】:2014-11-19 16:10:09
【问题描述】:

我有一个特定类型的DecodeJson[A] 实例A,我有一个Json 实例,称之为j。我想做类似j.as[List[A]] 的事情。但是,这个 JSON 来自第 3 方,如果数组中的某些项目缺少字段,我只想记录这些项目的错误并只收集可以正确解析的项目(而不是整个解码失败)。

在我看来,我想最终得到的结果类似于(List[(String, CursorHistory)], List[A])。也就是说,任何成功解码的元素都将在右侧列表中结束,而任何无法成功解析的项目的错误将在左侧累积。这看起来很像 scalaz 中的 MonadPlus.separate 方法。

我能想到几种到达那里的方法。一种方法是执行以下操作:

j.as[List[Json]].map(_.map(_.as[A].result).separate)

这应该会根据需要给我一个DecodeResult[List[(String, CursorHistory)], List[A]]。但是,这将丢弃有关失败项目在 JSON 数组中的位置的光标信息。我可以使用zipWithIndex 之类的东西,但这开始变得非常混乱。

在我看来,更好的解决方案是做这样的事情:

implicit def DecodeResultDecodeJson[A: DecodeJson]: DecodeJson[DecodeResult[A]] =
  decodeArr(_.as[A]) // outer DecodeResult is always a success

j.as[List[DecodeResult[A]]].map(_.map(_.result)).separate)

这将为我提供相同的输出类型,但应填充 CursorHistory 以包含有关步入数组元素的信息。

这是一个例子:

val j = Json.array(List("1", "2", "foo").map(Json.jString): _*)
val r = j.as[List[DecodeResult[Int]]].map(_.map(_.result).separate)
// r is DecodeResult[(List[(String, CursorHistory)], List[Int])] =
// DecodeResult(\/-((List((Int,CursorHistory([->,->,\\]))),List(1, 2))))

这似乎是合理的(忽略可能发生的一些可怕的列表连接)。然而,这种事情似乎是一个相当常见的用例,所以我想知道是否有更简单或内置的方法来做这样的事情。如果没有,我可能会为 DecodeJson[DecodeJson[A]] 实例向 argonaut 提交 PR,看看是否有人感兴趣。

【问题讨论】:

    标签: scala scalaz argonaut


    【解决方案1】:

    您可以使用HCursor 解码器,而不是保留历史记录的Json 解码器:

    j.as[List[HCursor]].map(_.map(_.as[Int].result).separate)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      相关资源
      最近更新 更多