Are you looking to find out how to parse a MapType column into StringType column
of PySpark DataFrame in the Azure Databricks cloud, or maybe you are looking for a solution, to parse an ArrayType into a StringType
in PySpark Databricks using the to_json() function? If you are looking for any of these problem solutions, you have landed on the correct page. I will also help you how to use the PySpark to_json() function with multiple examples in Azure Databricks. I will explain it by taking a practical example. So please don’t waste time let’s start with a step-by-step guide to understand how to use the to_json() function in PySpark.
In this blog, I will teach you the following with practical examples:
- Syntax of to_json()
- Converting MapType column into StringType
- Converting List of MapType column into StringType
- Converting ArrayType column into StringType
The PySpark function to_json() is used to convert a column containing a StructType, ArrayType or a MapType into a JSON string. in Azure Databricks.
Syntax:
to_json()
Contents
- 1 What is the syntax of the to_json() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to convert a MapType column into StringType in PySpark Azure Databricks?
- 4 How to convert a List of MapType column into StringType in PySpark Azure Databricks?
- 5 How to convert an ArrayType column into StringType in PySpark Azure Databricks?
- 6 When should you use the PySpark to_json() in Azure Databricks?
- 7 Real World Use Case Scenarios for PySpark DataFrame to_json() in Azure Databricks?
- 8 What are the alternatives to the to_json() function in PySpark Azure Databricks?
- 9 Final Thoughts
What is the syntax of the to_json() function in PySpark Azure Databricks?
The syntax is as follows:
to_json(column, schema, options)
Parameter Name | Required | Description |
column (str, Column) | Yes | It represents the name of a column containing a struct, an array, or a map. |
options (dict) | Optional | It controls the conversion, you can see the options by clicking here |
Apache Spark Official documentation link: to_json()
Create a simple DataFrame
Let’s understand the use of the to_json() function with a variety of examples. Let’s start by creating a DataFrame.
Gentle reminder:
In Databricks,
- sparkSession made available as spark
- sparkContext made available as sc
In case, you want to create it manually, use the below code.
from pyspark.sql.session import SparkSession
spark = SparkSession.builder
.master("local[*]")
.appName("azurelib.com")
.getOrCreate()
sc = spark.sparkContext
a) Create manual PySpark DataFrame
data = [
{"id": 1, "name": {"first_name": "Etta", "last_name": "Burrel"}, "details": [{"gender": "Female"}, {"age": "46"}], "preferences": ["District of Columbia", "Colorado"]},
{"id": 2, "name": {"first_name": "Ky", "last_name": "Fiddyment"}, "details": [{"gender": "Male"}, {"age": "35"}], "preferences": ["California", "Massachusetts"]},
{"id": 3, "name": {"first_name": "Rod", "last_name": "Meineken"}, "details": [{"gender": "Male"}, {"age": "50"}], "preferences": ["North Carolina", "Minnesota"]},
{"id": 4, "name": {"first_name": "Selestina", "last_name": "Ley"}, "details": [{"gender": "Female"}, {"age": "47"}], "preferences": ["Michigan", "Pennsylvania"]},
{"id": 5, "name": {"first_name": "Alvan", "last_name": "Shee"}, "details": [{"gender": "Male"}, {"age": "34"}], "preferences": ["Montana", "California"]}
]
df = spark.createDataFrame(data).select("id", "name", "details", "preferences")
df.printSchema()
df.show(truncate=False)
"""
root
|-- id: long (nullable = true)
|-- name: map (nullable = true)
| |-- key: string
| |-- value: string (valueContainsNull = true)
|-- details: array (nullable = true)
| |-- element: map (containsNull = true)
| | |-- key: string
| | |-- value: string (valueContainsNull = true)
|-- preferences: array (nullable = true)
| |-- element: string (containsNull = true)
+---+-------------------------------------------+---------------------------------+--------------------------------+
|id |name |details |preferences |
+---+-------------------------------------------+---------------------------------+--------------------------------+
|1 |{last_name -> Burrel, first_name -> Etta} |[{gender -> Female}, {age -> 46}]|[District of Columbia, Colorado]|
|2 |{last_name -> Fiddyment, first_name -> Ky} |[{gender -> Male}, {age -> 35}] |[California, Massachusetts] |
|3 |{last_name -> Meineken, first_name -> Rod} |[{gender -> Male}, {age -> 50}] |[North Carolina, Minnesota] |
|4 |{last_name -> Ley, first_name -> Selestina}|[{gender -> Female}, {age -> 47}]|[Michigan, Pennsylvania] |
|5 |{last_name -> Shee, first_name -> Alvan} |[{gender -> Male}, {age -> 34}] |[Montana, California] |
+---+-------------------------------------------+---------------------------------+--------------------------------+
"""
b) Creating a DataFrame by reading files
Download and use the below source file.
# replace the file_path with the source file location which you have downloaded.
df_2 = spark.read.format("json").load(file_path)
df_2.printSchema()
"""
root
|-- id: long (nullable = true)
|-- name: map (nullable = true)
| |-- key: string
| |-- value: string (valueContainsNull = true)
|-- details: array (nullable = true)
| |-- element: map (containsNull = true)
| | |-- key: string
| | |-- value: string (valueContainsNull = true)
|-- preferences: array (nullable = true)
| |-- element: string (containsNull = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to convert a MapType column into StringType in PySpark Azure Databricks?
Let’s see how to convert a MapType column into a StringType of PySpark DataFrame in Azure Databricks using various methods.
Example:
from pyspark.sql.functions import to_json
df1 = df.select("name", to_json("name").alias("str_name"))
df1.printSchema()
df1.show(truncate=False)
"""
Output:
root
|-- name: map (nullable = true)
| |-- key: string
| |-- value: string (valueContainsNull = true)
|-- str_name: string (nullable = true)
+-------------------------------------------+--------------------------------------------+
|name |str_name |
+-------------------------------------------+--------------------------------------------+
|{last_name -> Burrel, first_name -> Etta} |{"last_name":"Burrel","first_name":"Etta"} |
|{last_name -> Fiddyment, first_name -> Ky} |{"last_name":"Fiddyment","first_name":"Ky"} |
|{last_name -> Meineken, first_name -> Rod} |{"last_name":"Meineken","first_name":"Rod"} |
|{last_name -> Ley, first_name -> Selestina}|{"last_name":"Ley","first_name":"Selestina"}|
|{last_name -> Shee, first_name -> Alvan} |{"last_name":"Shee","first_name":"Alvan"} |
+-------------------------------------------+--------------------------------------------+
"""
How to convert a List of MapType column into StringType in PySpark Azure Databricks?
Let’s see how to convert a List of MapType column into a StringType of PySpark DataFrame in Azure Databricks using various methods.
Example:
from pyspark.sql.functions import to_json
df2 = df.select("details", to_json("details").alias("str_details"))
df2.printSchema()
df2.show(truncate=False)
"""
Output:
root
|-- details: array (nullable = true)
| |-- element: map (containsNull = true)
| | |-- key: string
| | |-- value: string (valueContainsNull = true)
|-- str_details: string (nullable = true)
+---------------------------------+----------------------------------+
|details |str_details |
+---------------------------------+----------------------------------+
|[{gender -> Female}, {age -> 46}]|[{"gender":"Female"},{"age":"46"}]|
|[{gender -> Male}, {age -> 35}] |[{"gender":"Male"},{"age":"35"}] |
|[{gender -> Male}, {age -> 50}] |[{"gender":"Male"},{"age":"50"}] |
|[{gender -> Female}, {age -> 47}]|[{"gender":"Female"},{"age":"47"}]|
|[{gender -> Male}, {age -> 34}] |[{"gender":"Male"},{"age":"34"}] |
+---------------------------------+----------------------------------+
"""
How to convert an ArrayType column into StringType in PySpark Azure Databricks?
Let’s see how to convert an ArrayType column into a StringType of PySpark DataFrame in Azure Databricks using various methods.
Example:
from pyspark.sql.functions import to_json
df3 = df.select("preferences", to_json("preferences").alias("str_preferences"))
df3.printSchema()
df3.show(truncate=False)
"""
Output:
root
|-- preferences: array (nullable = true)
| |-- element: string (containsNull = true)
|-- str_preferences: string (nullable = true)
+--------------------------------+-----------------------------------+
|preferences |str_preferences |
+--------------------------------+-----------------------------------+
|[District of Columbia, Colorado]|["District of Columbia","Colorado"]|
|[California, Massachusetts] |["California","Massachusetts"] |
|[North Carolina, Minnesota] |["North Carolina","Minnesota"] |
|[Michigan, Pennsylvania] |["Michigan","Pennsylvania"] |
|[Montana, California] |["Montana","California"] |
+--------------------------------+-----------------------------------+
"""
I have attached the complete code used in this blog in notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.
When should you use the PySpark to_json() in Azure Databricks?
These could be the possible reasons:
- For converting StructType into JSON string
- For converting ArrayType into JSON string
- For converting MapType into JSON string
Real World Use Case Scenarios for PySpark DataFrame to_json() in Azure Databricks?
Assume that you were given a requirement to convert all the ArrayType, MapType, and StructType columns into JSON strings. The PySpark to_json() function helps in converting those values into JSON strings.
What are the alternatives to the to_json() function in PySpark Azure Databricks?
The PySpark function to_json() is the only one that helps in converting the ArrayType, MapType, and StructType into JSON strings, and this function is clearly explained with multiple examples in the above section.
Final Thoughts
In this article, we have learned about the PySpark to_json() method of DataFrame in Azure Databricks along with the examples explained clearly. I have also covered different scenarios with practical examples that could be possible. I hope the information that was provided helped in gaining knowledge.
Please share your comments and suggestions in the comment section below and I will try to answer all your queries as time permits.
- For Azure Study material Join Telegram group : Telegram group link:
- Azure Jobs and other updates Follow me on LinkedIn: Azure Updates on LinkedIn
- Azure Tutorial Videos: Videos Link
- Azure Databricks Lesson 1
- Azure Databricks Lesson 2
- Azure Databricks Lesson 3
- Azure Databricks Lesson 4
- Azure Databricks Lesson 5
- Azure Databricks Lesson 6
- Azure Databricks Lesson 7
As a big data engineer, I design and build scalable data processing systems and integrate them with various data sources and databases. I have a strong background in Python and am proficient in big data technologies such as Hadoop, Hive, Spark, Databricks, and Azure. My interest lies in working with large datasets and deriving actionable insights to support informed business decisions.