簡體   English   中英

無法使用 spark scala 從 json 嵌套屬性中刪除“\”

[英]Unable to remove “\” from the json nested attributes using spark scala

我正在研究一個FHIR資源,在該資源中我得到一個 JSON 數據,如下所示:

{
    "appointmentRef": "Appointment/12213#4200",
    "encounterLengh": "2",
    "billingAccount": "savingsAccount",
    "hospitalization": "{\"preAdmissionIdentifierSystem\":\"https://system123445.html\",\"preAdmissionIdentifierValue\":\"pqr\",\"origin\":\"hospital\",\"admitSourceCode\":\"outp\",\"admitSourceReason\":\"some thing\",\"eid\":200,\"destination\":\"hospital\"}",
    "resourceType": "Encounter",
    "priority": "abc",
    "status": "triaged",
    "eid": "200",
    "subject": "Patient/435"
}

因此,以前對於位於根級別的屬性,例如appointmentRef參考等。他們在 R.HS 上也有"\" ,我可以通過我的代碼將其刪除。 但是,從上面的數據可以看出,對於嵌套屬性,我的代碼不起作用。

rowList.groupBy(row => row.key).foreach(rowList => {
        import com.google.gson.{Gson, JsonObject}
        val map: Map[String, String] = mutable.Map()
        rowList._2.foreach(row => {
          LOGGER.debug(s"row == $row")
          if (Utility.isBlank(row.jsonElementTag)) {
            val convertedObject = new Gson().fromJson(row.value, classOf[JsonObject])
            val itr = convertedObject.entrySet().iterator()
            while (itr.hasNext) {
              val next = itr.next()
              val value = next.getValue.getAsString
              val key = next.getKey
              LOGGER.debug(s"key-- $key value --$value")
              map.put(key, value)
            }
          }
          else {
            val convertedObject = new Gson().fromJson(row.value, classOf[JsonObject])
            LOGGER.debug(s"convertedObject  == $convertedObject")
            if (null != map.get(row.jsonElementTag).getOrElse(null)) {
              LOGGER.debug("map.get(row.jsonElementTag).get === "+row.jsonElementTag +" "+map.get(row.jsonElementTag).get)
              var array: JsonArray = new JsonArray
              val mapElement = new Gson().fromJson(map.get(row.jsonElementTag).get, classOf[JsonObject])
              array.add(mapElement)
              array.add(convertedObject)
              map.put(row.jsonElementTag, array.toString)
            }
            else {
              map.put(row.jsonElementTag, convertedObject.toString)
            }
          }
        })

我只是從數據框中獲取行並遍歷行,將其作為字符串,並將其放入鍵值對中。 if循環將為父級屬性運行, else-if循環將為嵌套屬性執行。

我什至嘗試了更簡單的replace("\","")方法,但沒有奏效。 那么,如何從嵌套屬性中刪除"\"

expected的 output 在我的嵌套 JSON 屬性中應該沒有"\"

hospitalization列是字符串類型,它包含json object 要將字符串提取或轉換為 json,請根據該列中的數據准備schema

檢查下面的代碼。

scala> import org.apache.spark.sql.types._                                                                                                                                                         
import org.apache.spark.sql.types._                                                                                                                                                                
                                                                                                                                                                                                   
scala> val schema = DataType.fromJson("""{"type":"struct","fields":[{"name":"admitSourceCode","type":"string","nullable":true,"metadata":{}},{"name":"admitSourceReason","type":"string","nullable"
:true,"metadata":{}},{"name":"destination","type":"string","nullable":true,"metadata":{}},{"name":"eid","type":"long","nullable":true,"metadata":{}},{"name":"origin","type":"string","nullable":tr
ue,"metadata":{}},{"name":"preAdmissionIdentifierSystem","type":"string","nullable":true,"metadata":{}},{"name":"preAdmissionIdentifierValue","type":"string","nullable":true,"metadata":{}}]}""").
asInstanceOf[StructType]                                                                                                                                                                           
scala> df.withColumn("hospitalization",from_json($"hospitalization",schema)).printSchema                                                                                                           
root                                                                                                                                                                                               
 |-- appointmentRef: string (nullable = true)                                                                                                                                                      
 |-- billingAccount: string (nullable = true)                                                                                                                                                      
 |-- eid: string (nullable = true)                                                                                                                                                                 
 |-- encounterLengh: string (nullable = true)                                                                                                                                                      
 |-- hospitalization: struct (nullable = true)                                                                                                                                                     
 |    |-- admitSourceCode: string (nullable = true)                                                                                                                                                
 |    |-- admitSourceReason: string (nullable = true)                                                                                                                                              
 |    |-- destination: string (nullable = true)                                                                                                                                                    
 |    |-- eid: long (nullable = true)                                                                                                                                                              
 |    |-- origin: string (nullable = true)                                                                                                                                                         
 |    |-- preAdmissionIdentifierSystem: string (nullable = true)                                                                                                                                   
 |    |-- preAdmissionIdentifierValue: string (nullable = true)                                                                                                                                    
 |-- priority: string (nullable = true)                                                                                                                                                            
 |-- resourceType: string (nullable = true)                                                                                                                                                        
 |-- status: string (nullable = true)                                                                                                                                                              
 |-- subject: string (nullable = true)                                                                                                                                                             
scala> df.withColumn("hospitalization",from_json($"hospitalization",schema)).show(false)                                                                                                           
+----------------------+--------------+---+--------------+---------------------------------------------------------------------------+--------+------------+-------+-----------+                   
|appointmentRef        |billingAccount|eid|encounterLengh|hospitalization                                                            |priority|resourceType|status |subject    |                   
+----------------------+--------------+---+--------------+---------------------------------------------------------------------------+--------+------------+-------+-----------+                   
|Appointment/12213#4200|savingsAccount|200|2             |[outp, some thing, hospital, 200, hospital, https://system123445.html, pqr]|abc     |Encounter   |triaged|Patient/435|                   
+----------------------+--------------+---+--------------+---------------------------------------------------------------------------+--------+------------+-------+-----------+                   

更新

創建了小助手 class 以在沒有架構的情況下提取或轉換 json。

  import org.apache.spark.sql.functions._
  import org.apache.spark.sql.expressions._
  import org.json4s.JsonDSL._
  import org.json4s._
  import org.json4s.jackson.JsonMethods._

  val append = udf((rowId: Long,json: String) => {
    compact(render(Map("rowId" -> parse(rowId.toString),"data" ->parse(json))))
  })

  implicit class DFHelper(df: DataFrame) {
    import df.sparkSession.implicits._

    def parseJson = df.sparkSession.read.option("multiLine","true").json(df.map(_.getString(0)))

    //Convert string to json object or array of json object
    def extract(column: Column) = {

      val updatedDF = df.withColumn("rowId",row_number().over(Window.orderBy(lit(1))))
      val parsedDF = updatedDF.filter(column.isNotNull)
        .select(append($"rowid",column).as("row"))
        .parseJson

      updatedDF.join(
        parsedDF.select($"rowId",$"data".as(column.toString())),
        updatedDF("rowId") === parsedDF("rowId"),
        "left"
      )
          .drop("rowId") // Deleting added rowId column.
    }
  }
scala> df.extract($"hospitalization").printSchema()

root
 |-- appointmentRef: string (nullable = true)
 |-- billingAccount: string (nullable = true)
 |-- eid: string (nullable = true)
 |-- encounterLengh: string (nullable = true)
 |-- hospitalization: string (nullable = true)
 |-- priority: string (nullable = true)
 |-- resourceType: string (nullable = true)
 |-- status: string (nullable = true)
 |-- subject: string (nullable = true)
 |-- hospitalization: struct (nullable = true)
 |    |-- admitSourceCode: string (nullable = true)
 |    |-- admitSourceReason: string (nullable = true)
 |    |-- destination: string (nullable = true)
 |    |-- eid: long (nullable = true)
 |    |-- encounterLengh: string (nullable = true)
 |    |-- origin: string (nullable = true)
 |    |-- preAdmissionIdentifierSystem: string (nullable = true)
 |    |-- preAdmissionIdentifierValue: string (nullable = true)
scala> df.extract($"hospitalization").show(false)
+----------------------+--------------+---+--------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------+-------+-----------+------------------------------------------------------------------------------+
|appointmentRef        |billingAccount|eid|encounterLengh|hospitalization                                                                                                                                                                                                                        |priority|resourceType|status |subject    |hospitalization                                                               |
+----------------------+--------------+---+--------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------+-------+-----------+------------------------------------------------------------------------------+
|Appointment/12213#4200|savingsAccount|200|1             |{"encounterLengh": "1","preAdmissionIdentifierSystem":"https://system123445.html","preAdmissionIdentifierValue":"pqr","origin":"hospital","admitSourceCode":"outp","admitSourceReason":"some thing","eid":200,"destination":"hospital"}|abc     |Encounter   |triaged|Patient/435|[outp, some thing, hospital, 200, 1, hospital, https://system123445.html, pqr]|
+----------------------+--------------+---+--------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+--------+------------+-------+-----------+------------------------------------------------------------------------------+

也許這有幫助-

加載提供的測試數據

val data =
      """
        |{
        |    "appointmentRef": "Appointment/12213#4200",
        |    "encounterLengh": "2",
        |    "billingAccount": "savingsAccount",
        |    "hospitalization": "{\"preAdmissionIdentifierSystem\":\"https://system123445.html\",\"preAdmissionIdentifierValue\":\"pqr\",\"origin\":\"hospital\",\"admitSourceCode\":\"outp\",\"admitSourceReason\":\"some thing\",\"eid\":200,\"destination\":\"hospital\"}",
        |    "resourceType": "Encounter",
        |    "priority": "abc",
        |    "status": "triaged",
        |    "eid": "200",
        |    "subject": "Patient/435"
        |}
      """.stripMargin

    val ds = Seq(data).toDF()
    ds.show(false)
    ds.printSchema()

    /**
      * +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
      * |value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
      * +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
      * |
      * {
      * "appointmentRef": "Appointment/12213#4200",
      * "encounterLengh": "2",
      * "billingAccount": "savingsAccount",
      * "hospitalization": "{\"preAdmissionIdentifierSystem\":\"https://system123445.html\",\"preAdmissionIdentifierValue\":\"pqr\",\"origin\":\"hospital\",\"admitSourceCode\":\"outp\",\"admitSourceReason\":\"some thing\",\"eid\":200,\"destination\":\"hospital\"}",
      * "resourceType": "Encounter",
      * "priority": "abc",
      * "status": "triaged",
      * "eid": "200",
      * "subject": "Patient/435"
      * }
      * |
      * +------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
      *
      * root
      * |-- value: string (nullable = true)
      */

\替換為'' (空字符串)

    ds.withColumn("value", translate($"value", "\\", ""))
      .show(false)

    /**
      * +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
      * |value                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
      * +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
      * |
      * {
      * "appointmentRef": "Appointment/12213#4200",
      * "encounterLengh": "2",
      * "billingAccount": "savingsAccount",
      * "hospitalization": "{"preAdmissionIdentifierSystem":"https://system123445.html","preAdmissionIdentifierValue":"pqr","origin":"hospital","admitSourceCode":"outp","admitSourceReason":"some thing","eid":200,"destination":"hospital"}",
      * "resourceType": "Encounter",
      * "priority": "abc",
      * "status": "triaged",
      * "eid": "200",
      * "subject": "Patient/435"
      * }
      * |
      * +----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
      */

暫無
暫無

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

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