pawel.panasewicz
pawel.panasewicz

Reputation: 1833

read elements from json array in playframework scala

Given a json:

val json = """
{
  "persons": [
    {"name": "Foo", "age": 21},    
    {"name": "Bar", "age": 22},
    {"name": "Baz", "age": 23}
  ]
}
"""

How to construct a play Reads[List[String]] which will extract list of names form that json?

import play.api.libs.json._

val reads: Reads[List[String]] = ???

val names: List[String] = reads.reads(Json.parse(json)) 
// expecting List("Foo", "Bar", "Baz")

Upvotes: 0

Views: 672

Answers (2)

YouXiang-Wang
YouXiang-Wang

Reputation: 1127

Could try the workaround?


final case class Person(name: String, age: Int)
object Person {
  implicit val PersonFormat = Json.format[Person]
}


val jsonStr= """
{
  "persons": [
    {"name": "Foo", "age": 21},
    {"name": "Bar", "age": 22},
    {"name": "Baz", "age": 23}
  ]
}
"""

(Json.parse(jsonStr) \ "persons").as[List[Person]].map(p => p.name)



Or

((Json.parse(jsonStr) \ "persons") \\ "name").map(_.as[String])

Upvotes: 3

cchantep
cchantep

Reputation: 9158

Just compose with Reads.

import play.api.libs.json._

val input = Json.parse("""
{
  "persons": [
    {"name": "Foo", "age": 21},    
    {"name": "Bar", "age": 22},
    {"name": "Baz", "age": 23}
  ]
}
""")

val nameReads = (JsPath \ "name").read[String]
val listReads: Reads[Seq[String]] = Reads.seq(nameReads)

(input \ "persons").validate(listReads)
// JsSuccess(Vector(Foo, Bar, Baz),)

Upvotes: 1

Related Questions