我是斯卡拉的新手。我正在尝试使用json文件进行简单的操作。我坚持以下任务:如何在具有已定义名称的对象中删除具有已定义名称的字段。 作为一个例子,我想从对象名称2
中删除dsc1字段{
"group": {
"name1":{
"dsc":"some dsc",
"dsc1":"some dsc",
"dsc2":"some dsc"
},
"name2":{
"dsc":"some dsc",
"dsc1":"some dsc",
"dsc2":"some dsc"
}
}
}
解析我正在使用liftweb。 我已经修改了以下代码,但它删除了所有dsc1:
val transformedJson2 = parsedInput transform {
case JObject(fields) if (fields.head.name == "name2") => JObject(fields) transform {
case JField("dsc1", JArray(xs)) => JNothing
}
答案 0 :(得分:3)
我稍微重写了你的转换,当我尝试反对你的输入时,这似乎有效:
val transformedJson2 = parsedInput transform {
case JField("name2", fields) =>
fields remove {
case JField("dsc1", _) => true
case _ => false
}
}
您可以像在示例中一样使用第二个remove
,而不是使用transform
:
val transformedJson2 = parsedInput transform {
case JField("name2", fields) =>
fields transform {
case JField("dsc1", _) => JNothing
}
}
因此,通过使用来自:
的解析输入scala> val parsedInput = parse(""" {
| "group": {
| "name1":{
| "dsc":"some dsc",
| "dsc1":"some dsc",
| "dsc2":"some dsc"
| },
| "name2":{
| "dsc":"some dsc",
| "dsc1":"some dsc",
| "dsc2":"some dsc"
| }
| }
| } """)
parsedInput: net.liftweb.json.package.JValue = JObject(List(JField(group,JObject(List(JField(name1,JObject(List(JField(dsc,JString(some dsc)), JField(dsc1,JString(some dsc)), JField(dsc2,JString(some dsc))))), JField(name2,JObject(List(JField(dsc,JString(some dsc)), JField(dsc1,JString(some dsc)), JField(dsc2,JString(some dsc))))))))))
两者都应该产生输出:
scala> pretty(render(transformedJson2))
res10: String =
{
"group":{
"name1":{
"dsc":"some dsc",
"dsc1":"some dsc",
"dsc2":"some dsc"
},
"name2":{
"dsc":"some dsc",
"dsc2":"some dsc"
}
}
}
答案 1 :(得分:0)
我试过了:
val transformedJson2 = parsedInput transformField {
case JField("group", fields) => (
"group", fields transformField {
case JField("name2", nameFields) => (
"name2", nameFields removeField {
case JField("dsc1", _) => true
case _ => false
}
)
}
)
}
println(compact(render(transformedJson2)))