If you want to create a map from PersonalInfo column, from Spark 3.0 you can proceed as follows:
- Split your string according to
"","" using split function
- For each element of your obtained string array, create sub-arrays according to
"":"" using split function
- Remove all
"" from elements of sub-arrays using regexp_replace function
- Build map entries using
struct function
- Use
map_from_entries to build map from your array of entries
Complete code is as follows:
import org.apache.spark.sql.functions.{col, map_from_entries, regexp_replace, split, struct, transform}
val result = data.withColumn("PersonalInfo",
map_from_entries(
transform(
split(col("PersonalInfo"), "\"\",\"\""),
item => struct(
regexp_replace(split(item, "\"\":\"\"")(0), "\"\"", ""),
regexp_replace(split(item, "\"\":\"\"")(1), "\"\"", "")
)
)
)
)
With the following input_dataframe:
+-------+-------+---------------------------------------------------------------------------------------------+
|Empcode|EmpName|PersonalInfo |
+-------+-------+---------------------------------------------------------------------------------------------+
|1 |abc |""email"":""abc@gmail.com"",""Location"":""India"",""Gender"":""Male"" |
|2 |xyz |""email"":""xyz@gmail.com"",""Location"":""US"" |
|3 |pqr |""email"":""abc@gmail.com"",""Gender"":""Female"",""Location"":""Europe"",""Mobile"":""1234""|
+-------+-------+---------------------------------------------------------------------------------------------+
You get the following result dataframe:
+-------+-------+------------------------------------------------------------------------------+
|Empcode|EmpName|PersonalInfo |
+-------+-------+------------------------------------------------------------------------------+
|1 |abc |{email -> abc@gmail.com, Location -> India, Gender -> Male} |
|2 |xyz |{email -> xyz@gmail.com, Location -> US} |
|3 |pqr |{email -> abc@gmail.com, Gender -> Female, Location -> Europe, Mobile -> 1234}|
+-------+-------+------------------------------------------------------------------------------+