我有一个json,看起来像这样:
"A":{"B":1,"C":[{"D":2,"E":3},{"D":6,"E":7}]}
我想在此基础上创建一个包含两行的Dataframe。bde123167型在命令式语言中,我会使用for循环。但是,我发现scala不建议这样做,因此我想知道如何分解这个内部json并使用新行中的条目。非常感谢你
voase2hg1#
你可以用 from_json 要分析字符串json值:
from_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) )))) ) )
1条答案
按热度按时间voase2hg1#
你可以用
from_json
要分析字符串json值:也可以将架构作为structtype传递给
from_json
函数定义如下: