我有以下代碼:
class MyTest extends AnyFlatSpec with Matchers {
....
it should "calculate" in {
val testDf= Seq(
testDf(1, "customer1", "Hi"),
testDf(1, "customer2", "Hi")
).toDS().toDF()
val out = MyClass.procOut(spark, testDf)
out.count() should be(1)
out.where(col("customer_id")==="customer1").first().getString(output.first().fieldIndex("json_col")) should be(?) // Here I have problem!
}
}
我的問題:
out資料框是:
out.where(col("customer_id")==="customer1").first().getString(output.first().fieldIndex("json_col"))
提取 json 列,使其具有:
{
"statistics": {
"Group2": {
"buy": 1
}
}
}
我的目標是獲取buyeg 的值來斷言 json 中的值是 1。
所以我想做類似的事情:
out.where(col("customer_id")==="customer1").first().getString(output.first().fieldIndex("json_col")["statistics"]["Group2"]["buy"]) should be (1)
顯然這不是正確的語法,但我找不到從 json 中提取特定值的正確語法。
uj5u.com熱心網友回復:
json_tuple- 從 JSON 中提取資料并將它們創建為新列。
val jsonString="""{"Zipcode":704,"ZipCodeType":"STANDARD","City":"PARC PARQUE","State":"PR"}"""
val data = Seq((1, jsonString))
import spark.implicits._
val df=data.toDF("id","value")
import org.apache.spark.sql.functions.{json_tuple}
df.select(col("id"),json_tuple(col("value"),"Zipcode","ZipCodeType","City"))
.toDF("id","Zipcode","ZipCodeType","City")
.show(false)
get_json_object– 根據指定的 json 路徑從 JSON 字串中提取 JSON 元素。
import org.apache.spark.sql.functions.{get_json_object}
df.select(col("id"),get_json_object(col("value"),"$.ZipCodeType").as("ZipCodeType"))
.show(false)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/531447.html
標籤:斯卡拉阿帕奇火花
上一篇:BASH腳本-無法從grepped輸出中拆分字串并將其一一傳遞給變數
下一篇:確定日期在串列中是否連續
