首页 > 解决方案 > 如何删除密钥但保留孩子

问题描述

我是 Scala 新手,我正在尝试处理 json 文档。我将 scala 2.13.3 与以下库一起使用:

libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.0" % "test"
libraryDependencies += "org.json4s" %% "json4s-native" % "3.6.9"

问题是我找不到删除钥匙的方法,但仍然保留他的孩子如下:

这是开始的 json 文档:

{
  "Key": {
    "opt": {
      "attribute1": 0,
      "attribute2": 1,
      "attribute3": 2
    },
    "args": {
      "arg1": 0,
      "arg2": 1,
      "arg3": 2
    }
  }
}

我想删除"Key"只保留他的孩子"opt""args"以便我得到下面的 Json 文档:

{
  "opt": {
    "attribute1": 0,
    "attribute2": 1,
    "attribute3": 2
  },
  "args": {
    "arg1": 0,
    "arg2": 1,
    "arg3": 2
  }
}

我的代码

我使用Json4s库来操作文档,有一个transformField操作符允许对字段执行操作(key, value) => (key, value)。所以我试图定义一个空键"",但它不能满足我的需要。我也尝试只返回关联的值,但部分函数不允许它。

这是我的斯卡拉代码:

val json: JObject =
  "Key" -> (
    "opt" -> (
      ("attribute1" -> 0) ~
        ("attribute2" -> 1) ~
        ("attribute3" -> 2)
      ) ~
      ("args" -> (
        ("arg1", 0) ~
          ("arg2", 1) ~
          ("arg3", 2)
        )))

val res = json transformField {
  case JField("Key", attr) => attr
}

println(pretty(render(res)))

不幸的是,我不能只transformField用来转换("Key", attr)attr.


有没有一种简单的方法可以"Key"从我的 Json 中删除密钥,同时保留它的孩子"opt""args"

标签: jsonscalajson4s

解决方案


通常最好将 JSON 转换为 Scala 对象,操作 Scala 对象,然后再转换回 JSON。

这可能看起来像使用jackson

import org.json4s.{DefaultFormats, Extraction}
import org.json4s.jackson.{JsonMethods, Serialization}

val jsonIn = """
  {
    "Key": {
      "opt": {
        "attribute1": 0,
        "attribute2": 1,
        "attribute3": 2
      },
      "args": {
        "arg1": 0,
        "arg2": 1,
       "arg3": 2
     }
   }
 }
"""

case class Opt(attribute1: Int, attribute2: Int, attribute3: Int)
case class Args(arg1: Int, arg2: Int, arg3: Int)
case class Key(opt: Opt, args: Args)
case class DataIn(Key: Key)

implicit val formats = DefaultFormats

val dataIn: DataIn = Extraction.extract[DataIn](JsonMethods.parse(jsonIn))

val jsonOut: String = Serialization.write(dataIn.Key)

在这种情况下,Scala 处理只是从类中提取Key字段。DataIn

我在 Scala 2.12 上,所以 YMMV。


推荐阅读