与えられたRowオブジェクトをjsonに変換する簡単な方法はありますか? Spark 2でRowをjsonに変換する方法Scala
は、JSON出力に全体のデータフレームの変換についてこれを見つけた: Spark Row to JSONしかし、私はちょうどJSONに1行を変換したいです。 ここに私がしようとしているものの擬似コードがあります。
もっと正確には、私はDataframeの入力としてjsonを読んでいます。 私は主に列に基づいているが、列に収まらないすべての情報に対して1つの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のソリューション:行だけではない、ネストされた行に1つのレベルを持っている場合
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
}
ご意見ありがとうございます。私はあなたが接近しようとした: DEF row2DataFrame(行:行、sqlContext:SQLContext):DATAFRAME = { ヴァルsparkContext = sqlContext.sparkContext インポートsparkContext._ インポートsqlContext.implicits._ インポートsqlContext._ ヴァルrowRDD。 RDD [Row] = sqlContext.sparkContext.makeRDD(row :: Nil) val dataFrame = rowRDD.toDF()// XXXがコンパイルされない dataFrame } コンパイルされませんでした。 –