【发布时间】:2017-05-26 21:26:05
【问题描述】:
有没有一种简单的方法可以将给定的 Row 对象转换为 json?
发现这个关于将整个 Dataframe 转换为 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()
}
仅当 Row 只有一层而不是嵌套 Row 时才有效。这是架构:
StructType(
StructField(indicator,StringType,true),
StructField(range,
StructType(
StructField(currency_code,StringType,true),
StructField(maxrate,LongType,true),
StructField(minrate,LongType,true)),true))
也尝试了 Artem 的建议,但没有编译:
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
}
【问题讨论】:
标签: json scala apache-spark json4s