Surender Raja
Surender Raja

Reputation: 3599

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

"employees":[
{"firstName":"John", "lastName":"Doe"}, 
{"firstName":"Anna", "lastName":"Smith"}, 
{"firstName":"Peter","lastName":"Jones"}
]

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 scala.io.Source
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
    println(mySource)
    val parser = new JSONParser();
    val jArray = parser.parse(mySource);


 }

 }

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

Upvotes: 0

Views: 954

Answers (1)

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Using play-json

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

build.sbt

libraryDependencies ++= Seq("com.typesafe.play" %% "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 = """
"employees":[
              {"firstName":"John", "lastName":"Doe"}, 
              {"firstName":"Anna", "lastName":"Smith"}, 
              {"firstName":"Peter","lastName":"Jones"}
            ] """.stripMargin

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

val validJsonStr = "{" + str + "}"

Upvotes: 1

Related Questions