【发布时间】: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"?
【问题讨论】:
-
注意:Json4s 是 vulnerable under DoS/DoW attacks!