I have a table with two columns id, json_string and need to convert json_string into a MongoDB document format. I'm sending data from Spark/Scala to MongoDB.
I tried using withColumn but I still don't get the desired format. This is what I have so far, so any help would be really appreciated.
Original json string sample (df)
val df=spark.sql("select id, json_string from mytable")
{"id":"0001","json_string":"{\"header\": {\"column1\":\"value1\",\"column2\":\"value2\"},\"tail\": [{\"column3\":\"value3\",\"column4\":\"value4\",\"column5\":\"value5\"}]}"}
Using withColumn (df2) I get this:
val df2=df.withColumn("json_string",from_json(col("json_string"),MapType(StringType,StringType)))
{"id":"0001","json_string":{"header":"{\"column1\":\"value1\",\"column2\":\"value2\"}","tail":"[{\"column3\":\"value3\",\"column4\":\"value4\",\"column5\":\"value5\"}]"}}
Desired format:
{"id":{"$id":"0001"},"header":{"column1":"value1","column2":"value2"},"tail":[{"column3":"value3","column4":"value4","column5":"value5"}]}