2016-08-01 36 views
0

我想使用Scala讀取csv文件並將輸出存儲爲Json列表(list(json.obj))。斯卡拉閱讀文件,並在列表中加載爲json對象

這裏是我的代碼:

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 
} 

所以我的目標是存儲這是我從a.csv文件中讀取數據,並在jsonObjects名單,我將在以後使用加載到MongoDB中加載它。

+0

Thanks @marcospereira –

回答

0

你應該儘量避免使用變量。我認爲一個更好的解決方案可能是

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 
} 
0

@Mikel它現在的工作。感謝您的建議。

val surveyDB = parse("/Users/manujkathuria/a.csv") 

def parse(file: String): List[JsObject] = { 

    val bufferedSource = 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 
}