首页 > 解决方案 > 如何使用火花将列添加到json字段中

问题描述

我想在tt字段中添加一列。
我尝试了以下方法,但它不正确。我能怎么做?

val schema = StructType(
      Array(
        StructField("tt", StructType(
          Array(
            StructField("c1", StringType),
            StructField("c2", StringType)
          )
        ))
      )
    )

    val df = Seq(
      """
        |{"tt":
        |  {
        |  "c1":"F6",
        |  "c2":"mo"
        |  }
        |}
      """.stripMargin
    ).toDS

    val dff = spark.read.schema(schema).json(df)
    dff.printSchema()
//root
// |-- tt: struct (nullable = true)
// |    |-- c1: string (nullable = true)
// |    |-- c2: string (nullable = true)

    dff.withColumn("tt.tmp", lit("123")).show(false)
//+--------+-------------+
//|tt      |tt.tmp       |
//+--------+-------------+
//|[F6, mo]|123          |
//+--------+-------------+

标签: scalaapache-sparkapache-spark-sql

解决方案


推荐阅读