Skip to content

Instantly share code, notes, and snippets.

Created December 23, 2012 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4366212 to your computer and use it in GitHub Desktop.
Save anonymous/4366212 to your computer and use it in GitHub Desktop.
JSON Play2.1 : sample of function searching for nodes by filtering on key value
// searches for nodes by filtering on key value
def filter(jsv: JsValue, filterFn: String => Boolean): Seq[JsValue] = {
jsv match {
case JsObject(fields) => fields.toMap.foldLeft(Seq[JsValue]())((o, pair) => pair match {
case (key, value) if filterFn(key) => o ++ (value +: (filter(value, filterFn)))
case (_, value) => o ++ (filter(value, filterFn))
})
case _ => Seq[JsValue]()
}
}
scala> Json.obj("key1" -> Json.obj("toto1" -> "chboing"), "toto2" -> Json.arr( 1, 2, 3))
res31: play.api.libs.json.JsObject = {"key1":{"toto1":"chboing"},"toto2":[1,2,3]}
scala> res31
res32: play.api.libs.json.JsObject = {"key1":{"toto1":"chboing"},"toto2":[1,2,3]}
scala> filter(res31, s => if(s.startsWith("toto")) true else false)
res33: Seq[play.api.libs.json.JsValue] = List("chboing", [1,2,3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment