{
"people": [
{
"name": "Jack",
"age": 15
},
{
"name": "Tony",
"age": 23
},
{
"name": "Mike",
"age": 19
}
]
}
Thats a sample of the json I'm trying to parse through. I want to be able to do a foreach operation on each person and println their name and age.
I know how to handle json arrays when it's a single item or a specific numbered item. I don't know how to iterate through all items.
Can anyone help me out?
The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Argonaut is a great library. It's by far the best JSON library for Scala, and the best JSON library on the JVM. If you're doing anything with JSON in Scala, you should be using Argonaut.
parse() is needed when you have a javascript string of json text and you want to turn it into an object. ("JSON-like" isn't a meaningful descriptor and suggests more leniency than the JSON spec allows. In practice, however, you'll find varying degrees of leniency in different implementations of JSON.
There are many ways to do this with the Play JSON Library. The main difference is the usage of Scala case class or not.
Given a simple json
val json = Json.parse("""{"people": [ {"name":"Jack", "age": 19}, {"name": "Tony", "age": 26} ] }""")
You can use case class and Json Macro to automatically parse the data
import play.api.libs.json._
case class People(name: String, age: Int)
implicit val peopleReader = Json.reads[People]
val peoples = (json \ "people").as[List[People]]
peoples.foreach(println)
Or without case class, manually
import play.api.libs.json._
import play.api.libs.functional.syntax._
implicit val personReader: Reads[(String, Int)] = (
(__ \ "name").read[String] and
(__ \ "age").read[Int]
).tupled
val peoples = (json \ "people").as[List[(String, Int)]]
peoples.foreach(println)
In other words, check the very complete documentation on this subject :) http://www.playframework.com/documentation/2.1.0/ScalaJson
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With