问题
I'm new to scala. I'm trying to make simple manipulations with json files. I'm stucked with the following task: how can I ellegant remove field with defined name within object with defined name. As an example I'd like to delete dsc1 field from the object name2
{
"group": {
"name1":{
"dsc":"some dsc",
"dsc1":"some dsc",
"dsc2":"some dsc"
},
"name2":{
"dsc":"some dsc",
"dsc1":"some dsc",
"dsc2":"some dsc"
}
}
}
For parsing I'm using liftweb. I've cteate the following code but it deletes all dsc1:
val transformedJson2 = parsedInput transform {
case JObject(fields) if (fields.head.name == "name2") => JObject(fields) transform {
case JField("dsc1", JArray(xs)) => JNothing
}
回答1:
I rewrote your transformation a little bit, and this seemed to worked when I tried it against your input:
val transformedJson2 = parsedInput transform {
case JField("name2", fields) =>
fields remove {
case JField("dsc1", _) => true
case _ => false
}
}
Instead of using remove
, you could also use a second transform
as you did in your example:
val transformedJson2 = parsedInput transform {
case JField("name2", fields) =>
fields transform {
case JField("dsc1", _) => JNothing
}
}
So, by using the parsed input from:
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))))))))))
Both should yield the output:
scala> pretty(render(transformedJson2))
res10: String =
{
"group":{
"name1":{
"dsc":"some dsc",
"dsc1":"some dsc",
"dsc2":"some dsc"
},
"name2":{
"dsc":"some dsc",
"dsc2":"some dsc"
}
}
}
回答2:
I tried this:
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)))
来源:https://stackoverflow.com/questions/14216069/scala-remove-field-from-json-files-in-the-nested-object-with-defined-name