【问题标题】:Remove key from array of json using circe使用 circe 从 json 数组中删除键
【发布时间】:2021-01-24 06:21:14
【问题描述】:

我有一个json:

[
  {
    "a": "a",
    "b": "b",
    "c": "c"
  },
  {
    "a": "a1",
    "b": "b1",
    "c": "c1"
  }
]

现在,我想删除c 的密钥。所以结果是:

[
  {
    "a": "a",
    "b": "b"
  },
  {
    "a": "a1",
    "b": "b1"
  }
]

我用的是circe,到现在为止我做的是:

parse(entityAs[String]) match {
  case Right(value) =>
    val json = value.hcursor
    val result = json.downArray.downField("c").delete
    println(">>>>>>>>>>>>>>>>>")
    println(result.right.as[List[Json]])
         
  case Left(_) =>
}

这条线有问题

val result = json.downArray.downField("c").delete

删除密钥 c 然后使用 circe 将其转换回 json 列表的正确行是什么?

【问题讨论】:

    标签: scala scala-collections circe


    【解决方案1】:

    delete 在元素被删除的地方返回一个光标。您想取回整个文档,可以使用top 导航回顶部。您将取回修改后的文档。给定

    val doc = parse(entityAs[String])
    

    一起登上顶峰

    doc.hcursor.downArray.downField("c").delete.top
    

    会给你

    Some([
      {
        "a" : "a",
        "b" : "b"
      },
      {
        "a" : "a1",
        "b" : "b1",
        "c" : "c1"
      }
    ])
    

    但据我了解,您也想删除下一个“c”。那是

    doc.hcursor.downArray.downField("c").delete.right.downField("c").delete.top
    

    或者,全部删除

    def removeCs(element: ACursor): ACursor = {
      val deleted = element.downField("c").delete
      val focus = deleted.success.getOrElse(element)
      focus.right.success match {
        case Some(next) => removeCs(next)
        case None => focus
      }
    }
    
    removeCs(doc.hcursor.downArray).top
    

    【讨论】:

      猜你喜欢
      • 2021-08-25
      • 2019-09-15
      • 1970-01-01
      • 2021-01-22
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      相关资源
      最近更新 更多