简体   繁体   中英

scala iterate over JSON Array

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

在此处输入图片说明

While the scala.util.parsing.j‌son.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.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM