I am trying to read a comma delimited csv file using pyspark version 2.4.5 and Databrick's spark-csv module. One of the field in the csv file has a json object as its value. The contents of the csv are as below
test.csv
header_col_1, header_col_2, header_col_3
one, two, three
one, {“key1”:“value1",“key2”:“value2",“key3”:“value3”,“key4”:“value4"}, three
Other solutions that I found had read options defined as "escape": '"', and 'delimiter': ",". This seems not to be working as the commas in the field in question are not enclosed in double quotes. Below is the source code that I am using to read the csv file
test.py
from pyspark.sql import SparkSession
import findspark
findspark.init()
spark = SparkSession.builder.appName('test').getOrCreate()
read_options = {
'header': 'true',
"escape": '"',
'delimiter': ",",
'inferSchema': 'false',
}
spark_df = spark.read.format('com.databricks.spark.csv').options(**read_options).load('test.csv')
print(spark_df.show())
Output of the above program is as shown below
+------------+-----------------+---------------+
|header_col_1| header_col_2| header_col_3|
+------------+-----------------+---------------+
| one| two| three|
| one| {“key1”:“value1"|“key2”:“value2"|
+------------+-----------------+---------------+