Parsing a JSON string like """["test",["aaa", "bbb", "ccc"]]"""
is easy using scala.util.parsing.json
:
// def jsonResponse = scala.io.Source.fromURL("http://en.wikipedia.org/w/api.php?format=json&action=opensearch&search=test").mkString
def jsonResponse = """["test",["aaa", "bbb", "ccc"]]"""
def responseStrings = scala.util.Try[List[String]] {
val Some(List("test", words: List[_])) = scala.util.parsing.json.JSON.parseFull(jsonResponse)
words.map{case w: String => w}
}
responseStrings.get foreach println
prints
aaa
bbb
ccc
How can I do this in such an easy way using Argonaut?
Heres how you would do this in Argonaut which doesn't rely on catching Match Error exceptions in the Try block.
object Argo {
import argonaut._
def argoTest(): Unit = {
val input = """["test",["aaa", "bbb", "ccc"]]"""
val js: Option[List[String]] = for {
json <- Parse.parseOption(input)
outerArray <- json.array
innerArray <- outerArray match {
case h :: arr :: rest => h.string.filter(_ == "test").flatMap(_ => arr.array)
case _ => None
}
} yield innerArray.flatMap(_.string)
println(js)
}
}