简体   繁体   中英

how to parse Json with multi-line values in scala using scala util JSON parser

Currently I am using below code to read a config file and parse it as JSON.

val fileContent= scala.io.Source.fromFile(<file-path>)
val jsonText= fileContent.getLines.mkString("\n")
val parsedJsonText = JSON.parseFull(jsonText).get.asInstanceOf[Map[String,Any]]

Sample content of Json file :

{ 
"hiveDB" : "db1",
"hiveTbl" : "T1",
"hiveQuery" : " select * from db2.T2 where somecol='whereCond' ",
"option" : "load"
}

This JSON parsing works fine for above given content of file. However, at times hiveQuery Tag can have quite a big query and value of this Tag can be in multiple lines ie it may have newline & spread accross multiple lines before closing doble-quote("). Example:

"hiveQuery" : " select col1,  \\line separator 
concat_ws("-", col1, col2) as col12,   \\line separator
concat(col3,col4) as col34    \\newline separator
from db2.T3 join db4.T5 \\newline separator
on T3.col1=T5.col1"

While reading above formatted file, it fails during JSON parsing.

Please assist if any suitable tweaking i can do in my code.

One quick way would be to remove the line breaks in the first place:

Replace:

val jsonText= fileContent.getLines.mkString("\n")

With:

val jsonText= fileContent.getLines.mkString

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