Surender Raja Surender Raja - 1 year ago 108
Scala Question

How to convert a records of a json file into a List in scala

I am doing some handson on Scala

I have a json file named simple.json

{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},

I want read this json file from and keep the values of this values in a scala List

Expected output :

List("John|Doe", "Anna|Smith", "Peter|Jones")

I am not able to proceed with the scala file

package pack1
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
object ss {

def main(args: Array[String]): Unit = {
val mySource=Source.fromFile("C:\\inputfiles\\simple.json").getLines().mkString
val parser = new JSONParser();
val jArray = parser.parse(mySource);



How do I proceed with the code to get the expected output

Answer Source

Using play-json

if you are using sbt project. Add following line to dependencies in your project.


libraryDependencies ++= Seq("" %% "play-json" % "2.5.4")

Source code

val lines = Source.fromFile("<file-path>").getLines.mkString
val json = Json.parse("{" + lines.replaceAll("""\n""", "").trim + "}")
val list = (json \ "employees").as[List[JsValue]]
           .map(name => s"""${(name \ "firstName").as[String]}|${(name \ "lastName").as[String]}""")

Scala REPL

scala>  import play.api.libs.json._

scala> val str = """ {"employees" : [ {"firstName":"John", "lastName":"Doe"} ] }""".trim
str: String = {"employees" : [ {"firstName":"John", "lastName":"Doe"} ] }

scala> val json = Json.parse(str)
json: play.api.libs.json.JsValue = {"employees":[{"firstName":"John","lastName":"Doe"}]}

scala> val list = (json \ "employees").as[List[JsValue]].map(name => s"""${(name \ "firstName").as[String]}|${(name \ "lastName").as[String]}""")
list: List[String] = List(John|Doe)

Note that below string is not a valid json

val str = """
              {"firstName":"John", "lastName":"Doe"}, 
              {"firstName":"Anna", "lastName":"Smith"}, 
            ] """.stripMargin

This has to be wrapped inside a { } for Json.parse to parse properly.

val validJsonStr = "{" + str + "}"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download