如何将 json 字符串解析为数据框中的字符串数组
How to parse a json string to an array of strings in dataframe
我是 Scala 的新手,刚刚花了 3 个小时试图弄清楚如何将一个简单的 json 字符串解析为数据帧中的字符串数组。
这是我的代码:
import spark.implicits._
import org.apache.spark.sql.functions._
...
emailsDf.select(from_json($"emails", Array[String])).show()
emailsDf
数据框有一个名为 "emails" 的列,每一行都是一个 json 字符串数组:["test1@mail.com", test2@mail.com, ...]
这是我收到的错误消息:
Description Resource Path Location Type
missing argument list for method apply in object Array Unapplied methods are only converted to functions when a function type is expected. You can make this conversion explicit by writing apply _ or apply()() instead of apply.
您可以使用 UDF 将字符串转换为数组。一个带有一些测试数据的小例子:
val df = Seq("[email1, email2, email3]", "[email4, email5]").toDF("emails")
val split_string_array = udf((emails: String) => {
emails.substring(1, emails.length - 1).split(",").map(_.trim)
})
val df2 = df.withColumn("emails", split_string_array($"emails"))
df2
现在将包含一个带有数组的列
root
|-- emails: array (nullable = true)
| |-- element: string (containsNull = true)
随心所欲。
我是 Scala 的新手,刚刚花了 3 个小时试图弄清楚如何将一个简单的 json 字符串解析为数据帧中的字符串数组。
这是我的代码:
import spark.implicits._
import org.apache.spark.sql.functions._
...
emailsDf.select(from_json($"emails", Array[String])).show()
emailsDf
数据框有一个名为 "emails" 的列,每一行都是一个 json 字符串数组:["test1@mail.com", test2@mail.com, ...]
这是我收到的错误消息:
Description Resource Path Location Type missing argument list for method apply in object Array Unapplied methods are only converted to functions when a function type is expected. You can make this conversion explicit by writing apply _ or apply()() instead of apply.
您可以使用 UDF 将字符串转换为数组。一个带有一些测试数据的小例子:
val df = Seq("[email1, email2, email3]", "[email4, email5]").toDF("emails")
val split_string_array = udf((emails: String) => {
emails.substring(1, emails.length - 1).split(",").map(_.trim)
})
val df2 = df.withColumn("emails", split_string_array($"emails"))
df2
现在将包含一个带有数组的列
root
|-- emails: array (nullable = true)
| |-- element: string (containsNull = true)
随心所欲。