簡體   English   中英

Scala:如何將我的輸入轉換為列表列表

[英]Scala:How to convert my input to list of list

我有以下輸入,

輸入

[level:1,firstFile:one,secondFile:secone,Flag:NA][level:1,firstFile:two,secondFile:sectwo,Flag:NA][level:2,firstFile:three,secondFile:secthree,Flag:NA]

低於輸出並正常工作,

List(List(one, two), List(three))
List(List(secone, sectwo), List(secthree))

但是,當我通過下面的輸入時,我得到的輸出是,

[level:1,firstFile:one,four,secondFile:secone,Flag:NA][level:1,firstFile:two,secondFile:sectwo,Flag:NA][level:2,firstFile:three,secondFile:secthree,Flag:NA]

作為輸出

List(List(), List(two), List(three))
List(List(), List(sectwo), List(secthree))

但是預期的輸出是

List(List(one, four, two), List(three))
List(List(secone, sectwo), List(secthree))

碼。

 val validJsonRdd = sc.parallelize(Seq(input)).flatMap(x => x.replace(",", "\",\"").replace(":", "\":\"").replace("[", "{\"").replace("]", "\"}").replace("}{", "}&{").split("&"))
        import org.apache.spark.sql.functions._
        val df = spark.read.json(validJsonRdd).orderBy("level").groupBy("level")
                .agg(collect_list("firstFile").as("firstFile"), collect_list("secondFile").as("secondFile"))
                .select(collect_list("firstFile").as("firstFile"), collect_list("secondFile").as("secondFile"))          

        val rdd = df.collect().map(row => (row(0).asInstanceOf[Seq[Seq[String]]], row(1).asInstanceOf[Seq[Seq[String]]]))
        val first = rdd(0)._1.map(x => x.toList).toList       
        val second = rdd(0)._2.map(x => x.toList).toList

     val firstInputcolumns =  first.map(_.filterNot(_ == null)) 
     val secondInputcolumns= second.map(_.filterNot(_ == null))
     println(firstInputcolumns)
     println(secondInputcolumns)

請幫助我更正代碼。

看起來您的替換項無法產生有效的JSON。 如果在第二個輸入上運行它們,則對於第一個輸入,您將獲得:

{"level":"1","firstFile":"one","four","secondFile":"secone","Flag":"NA"}

但是JSON是鍵值對的列表。 您不能僅僅讓“四個”像這樣獨立出來。 如果要將firstFile映射到列表,則應將一個和四個包裹在方括號中,並且JSON應該如下所示:

{"level":"1","firstFile":["one","four"],"secondFile":"secone","Flag":"NA"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM