How do I replace part of json sub tree in lift framework
I need to replace a branch of a json tree using the lift framework (v2.3). For example, I'd like to replace the "a3" branch with a new tree
{
'a': {
'a1': {
'a3': . . .
}
}
}
I am currently using a JValue and think I can do the replacement using the fold method recursively, but it seems verbose if I need to replace a branch that is several levels deep.
Is there a better way to do t开发者_StackOverflow中文版his?
Thanks.
No one else has answered, and I found a decent solution to share:
import net.liftweb.json.JsonParser._
import net.liftweb.json.JsonAST._
import net.liftweb.json.Printer._
// change any a3 fields at any depth of the tree
compact(render(a.transform {
case JField("a3", _) => JString("changed")
}))
// String = {"a":{"a1":{"a3":"changed"}}}
// will only change a.a1.a3
compact(render(a.transform {
case JField("a", lvl2) => lvl2 transform {
case JField("a1", lvl3) => lvl3 transform {
case JField("a3", _) => JString("changed")
}
}
}))
// String = {"a":{"a1":{"a3":"changed"}}}
The lift-json JValue class has a replace method.
val data = ...
val replacement = ...
val newData = data.replace("a" :: "a1" :: "a3" :: Nil, replacement)
精彩评论