Manuj Kathuria Manuj Kathuria - 4 months ago 22
JSON Question

Scala read file and load in list as json object

I am trying to read a csv file using Scala and store the output as a list of Json (

list(json.obj)
).

Here is my code:

def index = Action {
Logger.info("Application startup...")
var posts = List(Json.obj())
var finalPost = List(Json.obj())
val bufferedSource = Source.fromFile("/Users/manujkathuria/a.csv")
for (line <- bufferedSource.getLines) {
val cols = line.split(",").map(_.trim)
posts = List(
Json.obj(
"name" -> cols(0),
"age" -> cols(1),
"job" -> cols(2)
))
finalPost +: posts
}
bufferedSource.close
}


So my target is to store the data which I read from a.csv file and load it in the list of
jsonObjects
which I will use later for loading into MongoDB.

Answer

You should avoid the use of variables when you can. I think a better solution could be

def index = Action {
  Logger.info("Application startup...")
  val json = parse("/Users/manujkathuria/a.csv")
  ... 
}
def parse(file:String): List[Json] = {
  val bufferedSource = io.Source.fromFile(file)
  try {
    bufferedSource.getLines().map(line => {
      val cols = line.split(",").map(_.trim)
      Json.obj(
        "name" -> cols(0),
        "age" -> cols(1),
        "job" -> cols(2)
      )
    }).toList
  } finally
    bufferedSource.close
}
Comments