【问题标题】:Collecting Elements in a JSON Array收集 JSON 数组中的元素
【发布时间】:2019-04-26 19:14:40
【问题描述】:

我和 Argonaut 有很大的关系。我需要收集 JSON 数组中的所有元素。例如,我有 JSON 格式的数据。

val data = """{"id": 1, "items": [{"name": "foo","price": 10},{"name": "bar","price": 20}]}"""

然后我需要将所有name 值收集到列表中。所以我得到了这个

List("foo", "bar")

这意味着我需要遍历数组,所以我选择 Argonaut 库来执行此操作。但是很难知道 API 在 Argonaut 中是如何工作的。到目前为止,我有这个,

val data = """{"id": 1, "items": [{"name": "foo","price": 10},{"name": "bar","price": 20}]}""".parseOption

data flatMap (k =>
  +k --\ "items" flatMap (_.downArray) map (- _)
  )

但我不确定如何获取值。请我在这里需要建议。

【问题讨论】:

    标签: json scala argonaut


    【解决方案1】:

    如果您添加 argonaut-monocle,您可以轻松地执行以下操作:

    import argonaut._
    import Argonaut._
    import argonaut.JsonPath._
    
    scala> val json: Option[Json] = """{"id": 1, "items": [{"name": "foo","price": 10},{"name": "bar","price": 20}]}""".parseOption
    json: Option[argonaut.Json] = Some({"id":1,"items":[{"name":"foo","price":10},{"name":"bar","price":20}]})
    
    scala> root.items.each.name.string.getAll(json.get)
    res1: List[String] = List(foo, bar)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-24
      相关资源
      最近更新 更多