有没有一种简单的方法将给定的Row对象转换为json?
发现这有关将整个Dataframe转换为json输出: Spark Row到JSON
但我只想将一行转换为json.这是我想要做的伪代码.
更确切地说,我在数据帧中读取json作为输入.我正在生成一个主要基于列的新输出,但是有一个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)
})
}
Run Code Online (Sandbox Code Playgroud)
Psidom的解决方案:
def convertRowToJSON(row: Row): String = {
val m = row.getValuesMap(row.schema.fieldNames)
JSONObject(m).toString()
}
Run Code Online (Sandbox Code Playgroud)
仅当Row只有一个级别而不是嵌套Row时才有效.这是架构:
StructType(
StructField(indicator,StringType,true),
StructField(range,
StructType(
StructField(currency_code,StringType,true),
StructField(maxrate,LongType,true),
StructField(minrate,LongType,true)),true))
Run Code Online (Sandbox Code Playgroud)
还尝试了Artem的建议,但是没有编译:
def row2DataFrame(row: Row, …Run Code Online (Sandbox Code Playgroud)