Reputation: 5720
I have a very simple JSON as below and I want to get sJson[0], sJson[1]
objects, How can I achieve this ?
scala> val jsonA = "[{'foo': 4, 'bar': 'baz'},{'bla': 4, 'bar': 'bla'}]"
jsonA: String = [{'foo': 4, 'bar': 'baz'},{'bla': 4, 'bar': 'bla'}]
scala> val sJson = parseFull(jsonA)
sJson: Option[Any] = None
scala> println(sJson.toString())
None
Upvotes: 1
Views: 4821
Reputation: 578
While the scala.util.parsing.json.JSON works well it is best to use an external library like json4s which has a fluent scala api.
You can query json just like you query xml (like JsonPath).
Below are the steps how you can use json4s for your need once you have it in your project.
First add the following imports
import org.json4s._
import org.json4s.native.JsonMethods._
Now create a Jvalue by doing
val jsonA = """[{"foo": 4, "bar": "baz"},{"bla": 4, "bar": "bla"}]"""
val json = parse(jsonA)
Your json object is as
json: org.json4s.JValue = JArray(List(JObject(List((foo,JInt(4)), (bar,JString(baz)))), JObject(List((bla,JInt(4)), (bar,JString(bla))))))
To get the first (0th) child
val firstChild = (json)(0)
firstChild: org.json4s.JsonAST.JValue = JObject(List((foo,JInt(4)), (bar,JString(baz))))
To get a string representation of this firstChild
val firstChildString = compact(render(firstChild))
firstChildString: String = {"foo":4,"bar":"baz"}
See the section Querying JSON in json4s home page for more.
Note: to import the jars you can use maven/gradle or import them into scala repl by using :require command.
Upvotes: 2
Reputation: 2101
JSON notation wants you to surround variables with double quotes:
val jsonA = """[{"foo": 4, "bar": "baz"},{"bla": 4, "bar": "bla"}]"""
val sJson = parseFull(jsonA).get.asInstanceOf[List[Map[String,String]]] // List(Map(foo -> 4.0, bar -> baz), Map(bla -> 4.0, bar -> bla))
Upvotes: 2