json - 如何删除密钥但保留孩子
问题描述
我是 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"
?
解决方案
通常最好将 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。
推荐阅读
- python - 使用python下载网站
- machine-learning - 如何设计换班推荐系统?
- algorithm - Bin Packing中启发式算法和近似算法的区别
- android - 在将数据写入 Graphview 中的图形时,会得到一些额外的线。我该如何解决?
- c# - WPF XAML 列表框选定项边框颜色
- reactjs - reactjs this.props.history.goback 在android webview上不起作用
- mysql - 计算两条记录并将它们连接到同一 MySQL 行中
- sql - Amazon Redshift - 如何提取上个月的数据
- html - 如何删除水平滚动菜单下的指示器
- data-structures - 数组中的奇数