【发布时间】:2018-03-21 02:29:30
【问题描述】:
我在 DataFrame 中有一个列,其中包含字符串格式的嵌套 json
val df=Seq(("""{"-1":{"-1":[ 7420,0,20,22,0,0]}}""" ), ("""{"-1":{"-1":[1006,2,18,10,0,0]}}"""), ("""{"-1":{"-1":[6414,0,17,11,0,0]}}""")).toDF("column1")
+-------------------------------------+
| column1|
+-------------------------------------+
|{"-1":{"-1":[7420, 0, 20, 22, 0, 0]}}|
|{"-1":{"-1":[1006, 2, 18, 10, 0, 0]}}|
|{"-1":{"-1":[6414, 0, 17, 11, 0, 0]}}|
+-----------------------+-------------+
I want to get a data frame that looks like this
+----+----+----+----+----+----+----+----+
|col1|col2|col3|col4|col5|col6|col7|col8|
+----+----+----+----+----+----+----+----+
| -1| -1|7420| 0| 20| 22| 0| 0|
| -1| -1|1006| 2| 18| 10| 0| 0|
| -1| -1|6414| 0| 17| 11| 0| 0|
+----+----+----+----+----+----+----+----+
我首先申请了get_json_object,它给了我
val df1= df.select(get_json_object($"column1", "$.-1")
+------------------------------+
| column1|
+------------------------------+
|{"-1":[7420, 0, 20, 22, 0, 0]}|
|{"-1":[1006, 2, 18, 10, 0, 0]}|
|{"-1":[6414, 0, 17, 11, 0, 0]}|
+-----------------------+------+
所以我丢失了第一个元素。
我尝试将现有元素转换为我想要的格式
val schema = new StructType()
.add("-1",
MapType(
StringType,
new StructType()
.add("a1", StringType)
.add("a2", StringType)
.add("a3", StringType)
.add("a4", StringType)
.add("a5", StringType)
.add("a6", StringType)
.add("a7", StringType)
.add("a8", StringType)
.add("a9", StringType)
.add("a10", StringType)
.add("a11", StringType)
.add("a11", StringType)))
df1.select(from_json($"new2", schema ))
但它返回了一个包含所有空值的 1 列 DataFrame
【问题讨论】:
标签: scala apache-spark apache-spark-sql