gpt4 book ai didi

scala - 使用 Argonaut 映射 JSON 数组

转载 作者:行者123 更新时间:2023-12-04 22:59:52 24 4
gpt4 key购买 nike

我很难浏览 Argonaut 文档,所以我想我只需要一个简单的例子。

val input = """{"a":[{"b":4},{"b":5}]}"""

val output = ??? // desired value: List(4, 5)

我可以将光标移到数组:
Parse.parse(input).map((jObjectPL >=> jsonObjectPL("a") >=> jArrayPL)(_))
// scalaz.\/[String,Option[scalaz.IndexedStore[argonaut.Argonaut.JsonArray,
// argonaut.Argonaut.JsonArray,argonaut.Json]]] =
// \/-(Some(IndexedStoreT((<function1>,List({"b":4}, {"b":5})))))

但是然后呢?我在正确的轨道上吗?我什至应该为此使用游标吗?

编辑 - 我想这是一些进展。我为列表编写了一个解码器:
Parse.parse("""[{"b": 4}, {"b": 5}]""")
.map(_.as(IListDecodeJson(DecodeJson(_.downField("b").as[Int]))))
// scalaz.\/[String,argonaut.DecodeResult[scalaz.IList[Int]]] =
// \/-(DecodeResult(\/-([4,5])))

编辑 - 慢慢开始把它放在一起......
Parse.parse(input).map(_.as[HCursor].flatMap(_.downField("a").as(
IListDecodeJson(DecodeJson(_.downField("b").as[Int])))))
// scalaz.\/[String,argonaut.DecodeResult[scalaz.IList[Int]]] =
// \/-(DecodeResult(\/-([4,5])))

编辑 - 所以我想到目前为止我最好的解决方案是:
Parse.parse(input).map(_.as(
DecodeJson(_.downField("a").as(
IListDecodeJson(DecodeJson(_.downField("b").as[Int])).map(_.toList)
))
))

不过感觉有点啰嗦。

最佳答案

你可以用 new-ish Monocle 很好地做到这一点。支持 Argonaut(我在这里使用 Argonaut master,因为 6.1 里程碑仍在 Monocle 0.5 上):

import argonaut._, Argonaut._
import scalaz._, Scalaz._
import monocle._, Monocle._

val lens =
Parse.parseOptional ^<-?
jObjectPrism ^|-?
index("a") ^<-?
jArrayPrism ^|->>
each ^<-?
jObjectPrism ^|-?
index("b") ^<-?
jIntPrism

进而:
scala> lens.getAll("""{"a":[{"b":4},{"b":5}]}""")
res0: scalaz.IList[Int] = [4,5]

运算符起初看起来很糟糕,但你习惯了它们,组成的片段读起来很自然。当然,由于这是一个镜头,除了 getAll 之外,您还可以使用各种操作。 .

关于scala - 使用 Argonaut 映射 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29179897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com