spark dataframe 轉換 json


首先新建一個dataframe

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{SQLContext, SparkSession}
import scala.util.parsing.json.{JSON, JSONArray, JSONObject}

val conf = new SparkConf().setAppName("TTyb").setMaster("local")
val sc = new SparkContext(conf)
val spark = new SQLContext(sc)
val testDataFrame = spark.createDataFrame(Seq(
  ("1", "asf"),
  ("2", "2143"),
  ("3", "rfds")
)).toDF("label", "col")
testDataFrame.show()

打印結構是:

+-----+----+
|label| col|
+-----+----+
|    1| asf|
|    2|2143|
|    3|rfds|
+-----+----+

spark 自帶函數

val sparkFunction = testDataFrame.toJSON.collectAsList.toString
println(sparkFunction)
// 得到結果
// [{"label":"1","col":"asf"}, {"label":"2","col":"2143"}, {"label":"3","col":"rfds"}]

列表型json

但是如果想得到第一列為key,第二列為value,那么寫法是這樣子的:

val df2Array: Array[(String, String)] = testDataFrame.collect().map { row => (row(0).toString, row(1).toString) }
val jsonData: Array[JSONObject] = df2Array.map { i =>
  new JSONObject(Map(i._1 -> i._2))
}
val jsonArray:JSONArray = new JSONArray(jsonData.toList)
println(jsonArray)
// [{"1" : "asf"}, {"2" : "2143"}, {"3" : "rfds"}]

合並JSONArray key:value

但是上面發現每一個key:value都放在一個括號里面,怎么把他們合並成起來?只需要文本處理一下:

val df2Array: Array[(String, String)] = testDataFrame.collect().map { row => (row(0).toString, row(1).toString) }
val jsonData: Array[JSONObject] = df2Array.map { i =>
  new JSONObject(Map(i._1 -> i._2))
}
val jsTest = jsonData.mkString(",").replace("},{",",")
println(jsTest)
// {"1" : "asf","2" : "2143","3" : "rfds"}

怎么把這個字符串變成map通過key值來取得value?定義一下函數即可:

def regJson(json:Option[Any]):Map[String,Any] = json match {
case Some(map:Map[String,Any]) => map
}
println(regJson(JSON.parseFull(jsTest)))
// Map(1 -> asf, 2 -> 2143, 3 -> rfds)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM