简体   繁体   English

如何使用scala util JSON解析器在scala中使用多行值解析Json

[英]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.目前我正在使用下面的代码来读取配置文件并将其解析为 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 : Json 文件的示例内容:

{ 
"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.此 JSON 解析适用于上述给定的文件内容。 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标签可能有一个相当大的查询,并且这个标签的值可以在多行中,即它可能有换行符并在关闭双引号(“)之前跨多行展开。示例:

"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.读取上述格式化文件时,在 JSON 解析过程中失败。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM