有沒有簡單的方法將給定的Row對象轉換爲json?如何將行轉換爲Spark 2中的json Scala
發現這個約一整個數據幀轉換成JSON輸出: Spark Row to JSON
但我只是想將一個行轉換成JSON。 這是我正在嘗試做的僞代碼。
更確切地說,我正在讀取json作爲Dataframe中的輸入。 我正在生成一個主要基於列的新輸出,但是對於不適合列的所有信息使用一個json字段。
我的問題是什麼來寫這一功能的最簡單的方法:convertRowToJson()
def convertRowToJson(row: Row): String = ???
def transformVenueTry(row: Row): Try[Venue] = {
Try({
val name = row.getString(row.fieldIndex("name"))
val metadataRow = row.getStruct(row.fieldIndex("meta"))
val score: Double = calcScore(row)
val combinedRow: Row = metadataRow ++ ("score" -> score)
val jsonString: String = convertRowToJson(combinedRow)
Venue(name = name, json = jsonString)
})
}
Psidom的解決方案:
def convertRowToJSON(row: Row): String = {
val m = row.getValuesMap(row.schema.fieldNames)
JSONObject(m).toString()
}
只能如果該行只有不帶嵌套行的一個級別。這是模式:
StructType(
StructField(indicator,StringType,true),
StructField(range,
StructType(
StructField(currency_code,StringType,true),
StructField(maxrate,LongType,true),
StructField(minrate,LongType,true)),true))
也試過阿爾喬姆的想法,但是沒有編譯:
def row2DataFrame(row: Row, sqlContext: SQLContext): DataFrame = {
val sparkContext = sqlContext.sparkContext
import sparkContext._
import sqlContext.implicits._
import sqlContext._
val rowRDD: RDD[Row] = sqlContext.sparkContext.makeRDD(row :: Nil)
val dataFrame = rowRDD.toDF() //XXX does not compile
dataFrame
}
感謝您的建議。我想你的做法: 高清row2DataFrame(行:行,sqlContext:SQLContext):數據幀= { VAL sparkContext = sqlContext.sparkContext 進口sparkContext._ 進口sqlContext.implicits._ 進口sqlContext._ VAL rowRDD: RDD [行] = sqlContext.sparkContext.makeRDD(行::無) VAL數據幀= rowRDD.toDF()// XXX不編譯 數據幀 } 它沒有編譯。 –