parsing a Json Array in play framework JsObject
I'd argue that it's generally a good idea to move from JSON-land to native-Scala-representation-land as early as possible. If obj
is your JsObject
, for example, you can write this:
val subCategories = (obj \ "sub-categories").as[List[Map[String, String]]]val names = subCategories.map(_("name"))
Or even:
case class Category(name: String, subs: List[String])import play.api.libs.functional.syntax._implicit val categoryReader = ( (__ \ "web-category").read[String] and (__ \ "sub-categories").read[List[Map[String, String]]].map(_.map(_("name"))))(Category)
And then:
obj.as[Category]
This latter approach makes error handling even cleaner (e.g. you can just replace as
with asOpt
at this top level) and composes nicely with other Reads
type class instances—if you have a JsArray
of these objects, for example, you can just write array.as[List[Category]]
and get what you expect.
What Peter said, or:
(o \ "sub-categories" \\ "name").map(_.as[String]).toList
Something like this:
subCats.map( jsarray => jsarray.value.map(jsvalue => (jsvalue \ "name").as[String]).toList)
This will normally return a Option[List[String]]