How to extract column from JSON strings in PySpark Azure Databricks?

Are you looking to find out how to extract a column from a JSON string of PySpark DataFrame in Azure Databricks cloud or maybe you are looking for a solution, to create multiple columns out of a JSON string in PySpark Databricks using the get_json_object() 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 get_json_object() 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 get_json_object() function in PySpark.

In this blog, I will teach you the following with practical examples:

  • Syntax of get_json_object() functions
  • Extracting single column
  • Extracting multiple columns

The PySpark function get_json_object() is used to extract one column from a json column at a time in Azure Databricks.

Syntax:

get_json_object()

What is the syntax of the get_json_object() function in PySpark Azure Databricks?

The syntax is as follows:

get_json_object(json_column, sub_column)
Parameter NameRequiredDescription
json_column (str, Column)YesIt represents the column containing JSON values.
sub_column (str)YesIt represents the column name that has to be extracted.
Table 1: get_json_object() Method in PySpark Databricks Parameter list with Details

Apache Spark Official Documentation Link: get_json_object()

Create a simple DataFrame

Let’s understand the use of the get_json_object() function with various 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 extract a column from a column containing JSON string in PySpark Azure Databricks?

Let’s see how to extract a column from a column containing the JSON string of PySpark DataFrame in Azure Databricks using various methods.

Example:

# Method 1:

from pyspark.sql.functions import get_json_object, col

df.select(get_json_object("value", "$.Name").alias("car_name")) \
.show(truncate=False)

"""
Output:

+---------+
|car_name |
+---------+
|chevrolet|
+---------+

"""
# Method 2:

from pyspark.sql.functions import get_json_object, col

df.select(get_json_object(col("value"), "$.Origin").alias("car_origin")) \
.show(truncate=False)

"""
Output:

+----------+
|car_origin|
+----------+
|USA       |
+----------+

"""

How to extract multiple columns from a column containing JSON string in PySpark Azure Databricks?

Let’s see how to extract multiple columns from a column containing the JSON string of PySpark DataFrame in Azure Databricks using various methods.

Example:

from pyspark.sql.functions import get_json_object, col

df.select(
    get_json_object("value", "$.Name").alias("car_name"),
    get_json_object(col("value"), "$.Origin").alias("car_origin"),
).show(truncate=False)

"""
Output:

+---------+----------+
|car_name |car_origin|
+---------+----------+
|chevrolet|USA       |
+---------+----------+

"""

Note: The get_json_object() 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 get_json_object() in Azure Databricks?

You can use the PySpark get_json_object() function when you want to create a column out of JSON value.

Real World Use Case Scenarios for PySpark DataFrame get_json_object() in Azure Databricks?

Assuming that you want to create a column out of a JSON value, you can use PySpark’s get_json_object() to achieve this requirement.

What are the alternatives to the get_json_object() function in PySpark Azure Databricks?

You can use the json_tuple() function of PySpark DataFrame, the difference between the two is that you can extract multiple columns at once using this function.

Final Thoughts

In this article, we have learned about the PySpark json_tuple() method of a 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.

PySpark in Azure Databricks, as explained by Arud Seka Berne S on azurelib.com.

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.