Are you looking to find out how to create columns from a JSON string of PySpark DataFrame in Azure Databricks cloud or maybe you are looking for a solution, to create new columns out of a JSON string in PySpark Databricks using the json_tuple() 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 json_tuple() 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 json_tuple() function in PySpark.
In this blog, I will teach you the following with practical examples:
- Syntax of json_tuple() functions
- Creating new columns from JSON string
The PySpark function json_tuple() is used to create new columns from a json column of specified fields in Azure Databricks.
Syntax:
json_tuple()
Contents
- 1 What is the syntax of the json_tuple() function in PySpark Azure Databricks?
- 2 Create a simple DataFrame
- 3 How to create new columns from a column containing JSON string in PySpark Azure Databricks?
- 4 When should you use the PySpark json_tuple() in Azure Databricks?
- 5 Real World Use Case Scenarios for PySpark DataFrame json_tuple() in Azure Databricks?
- 6 What are the alternatives to the json_tuple() function in PySpark Azure Databricks?
- 7 Final Thoughts
What is the syntax of the json_tuple() function in PySpark Azure Databricks?
The syntax is as follows:
json_tuple(json_column, *sub_columns)
Parameter Name | Required | Description |
json_column (str, Column) | Yes | It represents the column containing JSON values. |
sub_columns (str) | Yes | It represents the column names which has to be extracted. |
Apache Spark Official documentation link: json_tuple()
Create a simple DataFrame
Let’s understand the use of the json_tuple() 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
json_string = "{'Name':'chevrolet', 'Miles_per_Gallon':18, 'Cylinders':8, 'Displacement':307, 'Horsepower':130, 'Weight_in_lbs':3504, 'Acceleration':12, 'Year':'1970-01-01', 'Origin':'USA'}"
df = spark.createDataFrame([(1, json_string)], schema=["id", "value"])
df.printSchema()
df.show(truncate=False)
"""
root
|-- id: long (nullable = true)
|-- value: string (nullable = true)
+---+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|id |value |
+---+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|1 |{'Name':'chevrolet', 'Miles_per_Gallon':18, 'Cylinders':8, 'Displacement':307, 'Horsepower':130, 'Weight_in_lbs':3504, 'Acceleration':12, 'Year':'1970-01-01', 'Origin':'USA'}|
+---+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
"""
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("csv").option("header", True).load(file_path)
df_2.printSchema()
"""
root
|-- id: long (nullable = true)
|-- value: string (nullable = true)
"""
Note: Here, I will be using the manually created DataFrame.
How to create new columns from a column containing JSON string in PySpark Azure Databricks?
Let’s see how to create new columns from a column containing JSON string of PySpark DataFrame in Azure Databricks using various methods.
Example:
# Method 1:
from pyspark.sql.functions import json_tuple
df.select(json_tuple("value", "Name").alias("car_name")) \
.show(truncate=False)
"""
Output:
+---------+
|car_name |
+---------+
|chevrolet|
+---------+
"""
# Method 2:
from pyspark.sql.functions import json_tuple, col
df.select(json_tuple(col("value"), "Name", "Origin").alias("car_name", "car_origin")) \
.show(truncate=False)
"""
Output:
+---------+----------+
|car_name |car_origin|
+---------+----------+
|chevrolet|USA |
+---------+----------+
"""
# Method 3:
from pyspark.sql.functions import json_tuple
extract_col_names = ["Name", "Displacement", "Horsepower"]
new_col_names = [str("car_") + col_name.lower() for col_name in extract_col_names]
df.select(json_tuple("value", *extract_row_names).alias(*new_col_names)) \
.show(truncate=False)
"""
Output:
+---------+----------------+--------------+
|car_name |car_displacement|car_horsepower|
+---------+----------------+--------------+
|chevrolet|307 |130 |
+---------+----------------+--------------+
"""
Note: The json_tuple() function returns null when the specified key is not present.
I have attached the complete code used in this blog in a notebook format to this GitHub link. You can download and import this notebook in databricks, jupyter notebook, etc.
When should you use the PySpark json_tuple() in Azure Databricks?
You can use the PySpark get_json_object() function when you want to create multiple columns out of a JSON value.
Real World Use Case Scenarios for PySpark DataFrame json_tuple() in Azure Databricks?
Assuming that you want to create multiple columns out of JSON value, you can use the PySpark json_tuple() to achieve this requirement.
What are the alternatives to the json_tuple() function in PySpark Azure Databricks?
You can use the get_json_object() function of PySpark DataFrame, the difference between the two is you can only extract one column using this function.
Final Thoughts
In this article, we have learned about the PySpark json_tuple() 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.