似乎 Spark SQL 中應該有一個類似于資料透視的函式,但我還沒有找到任何將 JSON 鍵轉換為 aa 值的解決方案。假設我有一個格式錯誤的 JSON(我無法更改其格式):
{"A long string containing serverA": {"x": 1, "y": 2}}
我該如何處理
{"server": "A", "x": 1, "y": 2}
?
我將 JSON 讀入 an 中sql.dataframe,然后希望按上述方式處理它們:
val cs = spark.read.json("sample.json")
.???
uj5u.com熱心網友回復:
如果我們只想使用 spark 函式而不使用 UDF,則可以使用from_json將 json 決議為映射(我們需要指定架構)。然后你只需要用火花函式提取資訊。一種方法如下:
val schema = MapType(
StringType,
StructType(Array(
StructField("x", IntegerType),
StructField("y", IntegerType)
))
)
spark.read.text("...")
.withColumn("json", from_json('value, schema))
.withColumn("key", map_keys('json).getItem(0))
.withColumn("value", map_values('json).getItem(0))
.withColumn("server",
// Extracting the server name with a regex
regexp_replace(regexp_extract('key, "server[^ ]*", 0), "server", ""))
.select("server", "value.*")
.show(false)
產生:
------ --- ---
|server|x |y |
------ --- ---
|A |1 |2 |
------ --- ---
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352950.html
標籤:json 斯卡拉 阿帕奇火花 apache-spark-sql
