如何将嵌套的json转换为特定的Dataframe

wvmv3b1j  于 2021-07-13  发布在  Spark
关注(0)|答案(1)|浏览(338)

我有一个json,看起来像这样:

"A":{"B":1,"C":[{"D":2,"E":3},{"D":6,"E":7}]}

我想在此基础上创建一个包含两行的Dataframe。
bde123167型
在命令式语言中,我会使用for循环。但是,我发现scala不建议这样做,因此我想知道如何分解这个内部json并使用新行中的条目。
非常感谢你

voase2hg

voase2hg1#

你可以用 from_json 要分析字符串json值:

val df = Seq(
  """"A":{"B":1,"C":[{"D":2,"E":3},{"D":6,"E":7}]}"""
).toDF("col")

val df1 = df.withColumn(
    "col",
    from_json(
      regexp_extract(col("col"), "\"A\":(.*)", 1), // extract the part after "A":
      lit("struct<B:int,C:array<struct<D:int,E:int>>>")
    )
  ).select(col("col.B"), expr("inline(col.C)"))

df1.show
//+---+---+---+
//|  B|  D|  E|
//+---+---+---+
//|  1|  2|  3|
//|  1|  6|  7|
//+---+---+---+

也可以将架构作为structtype传递给 from_json 函数定义如下:

val schema = StructType(Array(
    StructField("B", IntegerType, true),
    StructField("C", ArrayType(StructType(Array(
            StructField("D", IntegerType, true),
            StructField("E", IntegerType, true)
          ))))
  )
)

相关问题