【问题标题】:How to remove key but keep childs如何删除密钥但保留孩子
【发布时间】:2020-11-10 14:19:38
【问题描述】:

我是 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) 执行操作。所以我试图定义一个空键"",但它不能满足我的需要。我也尝试只返回关联的值,但偏函数不允许它。

这是我的 scala 代码:

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


有没有一种简单的方法可以从我的 Json 中删除 "Key" 键,同时保留其子级 "opt""args"

【问题讨论】:

标签: json scala json4s


【解决方案1】:

通常最好将 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 处理只是从 DataIn 类中提取 Key 字段。

我使用的是 Scala 2.12 所以 YMMV。

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 2020-10-20
    • 2019-09-19
    • 2018-06-29
    • 2013-01-25
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多