Skip to content

Instantly share code, notes, and snippets.

@mandubian
Created March 17, 2013 22:34
Show Gist options
  • Save mandubian/5183939 to your computer and use it in GitHub Desktop.
Save mandubian/5183939 to your computer and use it in GitHub Desktop.
Play2.1 JSON API: Reads a JsArray and then map on its elements applying Reads (cumulating errors)
// maybe we could add this one into Play...
// Reads a JsArray and then map on its elements applying Reads (cumulating errors)
def readJsArrayMap[A <: JsValue](transformEach: Reads[A]): Reads[JsArray] = Reads { js => js match {
case arr: JsArray =>
arr.value.foldLeft(JsSuccess(Seq[JsValue]()): JsResult[Seq[JsValue]]) { (acc, e) =>
acc.flatMap{ seq =>
e.transform(transformEach).map( v => seq :+ v )
}
}.map(JsArray(_))
case _ => JsError("expected JsArray")
}}
// yours specific reader
val myReads = (__ \ "key1").json.pickBranch(
readJsArrayFoldLeft(
(__ \ "key2").json.pickBranch(
readJsArrayFoldLeft(
(__ \ "id").json.copyFrom(__.json.pick)
)
)
)
)
@jeantil
Copy link

jeantil commented Mar 18, 2013

in myReads, shouldn't it be readJsArrayMap instead of readJsArrayFoldLeft ? :)

@dev-inigmas
Copy link

I don't suppose this is any closer to making into Play, like your comments suggest? I found the helper method to be very useful for transforming a JsArray as output for my web services.

Thanks,
David P.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment