Created
December 23, 2012 21:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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