How to infer JSON records schema in PySpark Azure Databricks?

Are you looking to find out how to parse and extract a JSON column structure in DDL format of PySpark DataFrame in Azure Databricks cloud or maybe you are looking for a solution, to extract and unwrap JSON columns in PySpark Databricks with the help of schema_of_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 schema_of_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 schema_of_json() function in PySpark.

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

  • Syntax of schema_of_json() functions
  • Extracting the JSON column structure
  • Using the extracted structure

The PySpark function schema_of_json() is used to parse and extract JSON string and infer their schema in DDL format using PySpark Azure Databricks.

Syntax:

schema_of_json()

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

The syntax is as follows:

get_json_object(json_column, options)
Parameter NameRequiredDescription
json_column (str, Column)YesIt represents the column containing JSON values.
options (dict)OptionalIt controls JSON parsing.
Table 1: schema_of_json() Method in PySpark Databricks Parameter list with Details

Apache Spark Official documentation link: schema_of_json()

Create a simple DataFrame

Let’s understand the use of the schema_of_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

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 JSON column structure in PySpark Azure Databricks?

Let’s see how to parse and extract a JSON string from a column and infer its schema in the DDL format of a PySpark DataFrame in Azure Databricks with a step-by-step method.

  • Get the value of the first JSON column
  • Pass the extracted value to the schema_of_json() function

Step 1:

first_json_record = df.select("value").collect()[0]["value"]

"""
Output:

{'Name':'chevrolet', 'Miles_per_Gallon':18, 'Cylinders':8, 'Displacement':307, 'Horsepower':130, 'Weight_in_lbs':3504, 'Acceleration':12, 'Year':'1970-01-01', 'Origin':'USA'}

"""

Step 2:

from pyspark.sql.functions import schema_of_json, lit

options = {
    'allowUnquotedFieldNames':'true',
    'allowSingleQuotes':'true',
    'allowNumericLeadingZeros': 'true'}

json_schema = df.select(
    schema_of_json(lit(first_json_record), options).alias("json_struct")
).collect()[0][0]

print(str("Extract schema in DDL format:\n") + json_schema)

"""
Output:

Extract schema in DDL format:
STRUCT<Acceleration: BIGINT, Cylinders: BIGINT, Displacement: BIGINT, Horsepower: BIGINT, Miles_per_Gallon: BIGINT, Name: STRING, Origin: STRING, Weight_in_lbs: BIGINT, Year: STRING>

"""

Note: There are various options available for controlling schema inferring.

How to use the DDL schema to unwrap all the sub-columns of PySpark DataFrame using Azure Databricks?

Let’s see how to use the DDL schema to unwrap all the sub-columns of PySpark DataFrame in Azure Databricks with a step-by-step method.

  • Convert JSON column to Struct
  • Get the sub-columns list
  • Use the select() function to unwrap it

Step 1:

from pyspark.sql.functions import from_json

json_df = df.select("id", from_json("value", json_schema).alias("json"))
json_df.printSchema()

"""
Output:

root
 |-- id: long (nullable = true)
 |-- json: struct (nullable = true)
 |    |-- Acceleration: long (nullable = true)
 |    |-- Cylinders: long (nullable = true)
 |    |-- Displacement: long (nullable = true)
 |    |-- Horsepower: long (nullable = true)
 |    |-- Miles_per_Gallon: long (nullable = true)
 |    |-- Name: string (nullable = true)
 |    |-- Origin: string (nullable = true)
 |    |-- Weight_in_lbs: long (nullable = true)
 |    |-- Year: string (nullable = true)

"""

In the above output, you can see the column structure has been changed from JSON string to Struct using the from_json() function.

Step 2:

sub_columns = json_df.select("json.*").columns
sub_columns = [str("json.") + column for column in sub_columns]
print("Modified sun columns:\n" + str(sub_columns))

"""
Output:

Modified sun columns:
['json.Acceleration', 'json.Cylinders', 'json.Displacement', 'json.Horsepower', 'json.Miles_per_Gallon', 'json.Name', 'json.Origin', 'json.Weight_in_lbs', 'json.Year']

"""

Step 3:

json_df.select("id", *sub_columns).show()

"""
Output:

+---+------------+---------+------------+----------+----------------+---------+------+-------------+----------+
| id|Acceleration|Cylinders|Displacement|Horsepower|Miles_per_Gallon|     Name|Origin|Weight_in_lbs|      Year|
+---+------------+---------+------------+----------+----------------+---------+------+-------------+----------+
|  1|          12|        8|         307|       130|              18|chevrolet|   USA|         3504|1970-01-01|
+---+------------+---------+------------+----------+----------------+---------+------+-------------+----------+

"""

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 schema_of_json() in Azure Databricks?

These could be the possible reasons:

  1. For extracting column structure
  2. Unwrapping sub-columns of DataFrame

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

  • Assume you have a CSV file of JSON values without a header and n number of columns init and you want to create a schema for it manually, just think how terrible it is and you will how much I might consume. By using the schema_of_json() function you can fetch the structure of that records.
  • You can use the obtained schema and unwrap all the nested columns.

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

The PySpark schema_of_json() function is the only option you can use for extracting the structure of records from a JSON value and this method has been explained with an example in the above section.

Final Thoughts

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