如何使用Scala从JSON文件中读取字符串列表
输出:如何使用Scala从JSON文件中读取字符串列表,json,scala,dataframe,apache-spark,Json,Scala,Dataframe,Apache Spark,输出: val df = spark.read.option("multiline", "true").json("/FileStore/tables/config-5.json") df.show() 代码: 用于(行打印(c)) //Matriccal.ApproxCountDistinct_func(listofStr) } 因为List col应该是一个字符串列表,所以我得到了WrappedArray(数
val df = spark.read.option("multiline", "true").json("/FileStore/tables/config-5.json")
df.show()
代码:
用于(行打印(c))
//Matriccal.ApproxCountDistinct_func(listofStr)
}
因为List col应该是一个字符串列表,所以我得到了WrappedArray(数字,单词)WrappedArray(数字,单词)。我需要列表(字符串)。我假设您需要从列表列中获取第二个元素,以便可以获取它:
for (row <- df.rdd.collect) {
var List_col =(row(0))
var Matricsdynamic = row(1)
List_col.foreach(c =>print(c) )
//MatricsCal.ApproxCountDistinct_func(listofStr)
}
您应该能够使用
WrappedArray
的toList
方法轻松地转换为字符串列表
假设您的JSON文件如下所示:
{“列表列”:[9,“word1”],“矩阵”:“ApproxCountDistinct”}
{“列表列”:[10,“word2”],“矩阵”:“完备性”}
您可以获取一个记录数组,每个记录都是一个列表[String]
import scala.collection.mutable
import spark.implicits._
val df = Seq(
(List("24", "text1"), "metric1"),
(List("12", "text2"), "metric2"),
(List("53", "text2"), "metric3"),
(List("13", "text3"), "metric4"),
(List("64", "text4"), "metric5")
).toDF("List-col", "Matrics")
val result: Array[String] = df.map{
row =>
row.get(0) match {
case t:mutable.WrappedArray[AnyRef] => t.last.toString
}
}.collect()
println(result.mkString("Array(", ", ", ")")) // Array(text1, text2, text2, text3, text4)
你好@ELinda我收到以下错误:command-224774884011382:1:错误:未找到:值列值列表:数组[List[String]=df.select(col(“List col”).collect.map((r:Row)=>r.getAs[wrappedaray[String]](0.toList)^command-224774884011382:1:错误:未找到:键入WrappedArray val列表:数组[List[String]=df.select(col(“List col”)).collect.map((r:Row)=>r.getAs[WrappedArray[String]](0.toList)您需要导入它:
import org.apache.spark.sql.functions.col
command-224774884011384:12:错误:未找到:值可变case t:mutable.WrappedArray[AnyRef]=>t.last.toString^command-224774884011384:12:错误:值last不是任何情况的成员t:mutable.WrappedArray[AnyRef]=>t.last.toString^add importimport scala.collection.mutable
能否提供List col
数据类型?请将df.printSchema()
输出添加到问题描述中
import scala.collection.mutable
import spark.implicits._
val df = Seq(
(List("24", "text1"), "metric1"),
(List("12", "text2"), "metric2"),
(List("53", "text2"), "metric3"),
(List("13", "text3"), "metric4"),
(List("64", "text4"), "metric5")
).toDF("List-col", "Matrics")
val result: Array[String] = df.map{
row =>
row.get(0) match {
case t:mutable.WrappedArray[AnyRef] => t.last.toString
}
}.collect()
println(result.mkString("Array(", ", ", ")")) // Array(text1, text2, text2, text3, text4)
import org.apache.spark.sql._
import org.apache.spark.sql.functions.col
val lists:Array[List[String]] = df.select(col("List-col")).collect.map(
(r: Row) => r.getAs[WrappedArray[String]](0).toList)