从StringType Spark.SQL提取json数据

从StringType Spark.SQL提取json数据,json,scala,apache-spark,etl,Json,Scala,Apache Spark,Etl,有一个配置单元表,其中有一列类型为string 如何将其转换为下面这样的结构化列? 我试图用初始模式恢复它,即数据在写入hdfs之前被结构化。但是json_数据是空的 val schema = StructType( Seq( StructField("A", ArrayType( StructType( Seq( StructField("S", StringType, nullable = true))

有一个配置单元表,其中有一列类型为string

如何将其转换为下面这样的结构化列?

我试图用初始模式恢复它,即数据在写入hdfs之前被结构化。但是json_数据是空的

val schema = StructType(
    Seq(
      StructField("A", ArrayType(
        StructType(
          Seq(
            StructField("S", StringType, nullable = true))
        )
      ), nullable = true)
    )
  )

val df3 = df2.withColumn("json_data", from_json(col("test_field_1"), schema))

df3.printSchema()

如果
test_field_1
的结构是固定的,并且您不介意自己“解析”字段,那么您可以使用来执行转换:

case类S(S:String)
def toArray:String=>Array[S]=\.replaceAll(“[\\[\\]]”和“).split(“,”).map(S=>S(S.trim))
val toArrayUdf=udf(toArray)
val df3=df2.withColumn(“json_数据”,toArrayUdf(col(“test_field_1”))
df3.printSchema()
df3.显示(错误)
印刷品

根目录
|--测试字段1:字符串(可空=真)
|--json_数据:数组(nullable=true)
||--元素:struct(containsnall=true)
|| |--S:string(nullable=true)
+------------------------+------------------------+
|测试_字段_1| json_数据|
+------------------------+------------------------+
|[str0]、[str1]、[str2].[str0]、[str1]、[str2]]|
+------------------------+------------------------+

棘手的部分是创建结构的第二层(
元素:struct
)。我已经使用case类
S
创建了这个结构。

您可以添加
desc-formatted-logical\u-control.test1问题?@Shu-hive>desc-logical_-control.test1;OK test_field_1 string test field 1所用时间:0.673秒,获取:1行有没有办法避免自己解析字段?我没有找到一个让我问你一些初始问题以外的信息。在写入hdfs之前,您可能有一些将类似结构划分为几列的想法,例如,或其他一些方便使用数据的方法。您可以尝试以支持嵌套结构(如拼花)的格式将数据写入hdfs,这样在再次读取数据时就不会遇到问题。
val df2 = spark.sql("select * from logical_control.test1")

df2.printSchema()
root
|-- test_field_1: string (nullable = true)
df2.show(false)
+------------------------+
|test_field_1            |
+------------------------+
|[[str0], [str1], [str2]]|
+------------------------+
root
|-- A: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- S: string (nullable = true)
val schema = StructType(
    Seq(
      StructField("A", ArrayType(
        StructType(
          Seq(
            StructField("S", StringType, nullable = true))
        )
      ), nullable = true)
    )
  )

val df3 = df2.withColumn("json_data", from_json(col("test_field_1"), schema))

df3.printSchema()
root
|-- test_field_1: string (nullable = true)
|-- json_data: struct (nullable = true)
|    |-- A: array (nullable = true)
|    |    |-- element: struct (containsNull = true)
|    |    |    |-- S: string (nullable = true)
df3.show(false)
+------------------------+---------+
|test_field_1            |json_data|
+------------------------+---------+
|[[str0], [str1], [str2]]|null     |
+------------------------+---------+