How to iterate org.json4s.JsonAST.JValue which is an array of JSON objects to separately work on each object in Scala?
The following is your json.
scala> jsonres2: org.json4s.JValue = JArray(List(JObject(List((abc,JString(1)), (de,JString(1)))), JObject(List((fgh,JString(2)), (ij,JString(4))))))
There are several ways.
use
for
syntaxfor { JArray(objList) <- json JObject(obj) <- objList} { // do something val kvList = for ((key, JString(value)) <- obj) yield (key, value) println("obj : " + kvList.mkString(","))}
convert to
scala.collection
objectval list = json.values.asInstanceOf[List[Map[String, String]]]//=> list: List[Map[String,String]] = List(Map(abc -> 1, de -> 1), Map(fgh -> 2, ij -> 4))
or
implicit val formats = DefaultFormatsval list = json.extract[List[Map[String,String]]]//=> list: List[Map[String,String]] = List(Map(abc -> 1, de -> 1), Map(fgh -> 2, ij -> 4))
and do something.
for (obj <- list) println("obj : " + obj.toList.mkString(","))
Both outputs are
obj : (abc,1),(de,1)obj : (fgh,2),(ij,4)
The document of json4s is here.