我有幾個 json 陣列
[{"key":"country","value":"aaa"},{"key":"region","value":"a"},{"key":"city","value":"a1"}]
[{"key":"city","value":"b"},{"key":"street","value":"1"}]
我需要將城市和街道價值提取到不同的列中。
使用get_json_object($"address", "$[2].value").as("city")通過它的數字獲取元素不起作用,因為陣列可能會丟失某些欄位。
相反,我決定將此陣列轉換為鍵 -> 值對的映射,但這樣做有困難。到目前為止,我只設法獲得了一組陣列。
val schema = ArrayType(StructType(Array(
StructField("key", StringType),
StructField("value", StringType)
)))
from_json($"address", schema)
退貨
[[country, aaa],[region, a],[city, a1]]
[[city, b],[street, 1]]
我不知道從這里去哪里。
val schema = ArrayType(MapType(StringType, StringType))
失敗
cannot resolve 'jsontostructs(`address`)' due to data type mismatch: Input schema array<map<string,string>> must be a struct or an array of structs.;;
我正在使用火花 2.2
uj5u.com熱心網友回復:
使用 UDF,我們可以輕松處理這個問題。在下面的代碼中,我使用 UDF 創建了一個地圖。我希望這足以滿足需要
import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._
val df1 = spark.read.format("text").load("file path")
val schema = ArrayType(StructType(Array(
StructField("key", StringType),
StructField("value", StringType)
)))
val arrayToMap = udf[Map[String, String], Seq[Row]] {
array => array.map { case Row(key: String, value: String) => (key, value) }.toMap
}
val dfJSON = df1.withColumn("jsonData",from_json(col("value"),schema))
.select("jsonData").withColumn("address", arrayToMap(col("jsonData")))
.withColumn("city", when(col("address.city").isNotNull, col("address.city")).otherwise(lit(""))).withColumn("street", when(col("address.street").isNotNull, col("address.street")).otherwise(lit("")))
dfJSON.printSchema()
dfJSON.show(false)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/474425.html
上一篇:如何以編程方式執行Scala測驗
