如何使用scala从json文件中读取字符串列表

rqqzpn5f  于 2021-05-27  发布在  Spark
关注(0)|答案(2)|浏览(463)
val df = spark.read.option("multiline", "true").json("/FileStore/tables/config-5.json")

df.show()

输出:

+--------------+-------------------+
|      List-col|            Matrics|
+--------------+-------------------+
|[number, word]|ApproxCountDistinct|
|[number, word]|       Completeness|
+--------------+-------------------+

代码:

for (row <- df.rdd.collect) {   
    var List_col =(row(0))
    var Matricsdynamic = row(1)
    List_col.foreach(c =>print(c) )

    //MatricsCal.ApproxCountDistinct_func(listofStr)
}

因为list col应该是一个字符串列表,所以我得到wrappedarray(number,word)wrappedarray(number,word)。我需要列表(字符串)。

bfrts1fy

bfrts1fy1#

您应该能够使用 toList 方法 WrappedArray .
假设您的json文件如下所示:

{"List-col": [9, "word1"], "Matrics": "ApproxCountDistinct"}
{"List-col": [10, "word2"], "Matrics": "Completeness"}

您可以获取一个记录数组,每个记录都是一个 List[String] .

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)
hec6srdp

hec6srdp2#

我假设您需要从list col中获取第二个元素,这样您就可以得到:

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)

相关问题