We use JSON files because they store data in a simple, organized way. Reading JSON helps us get this data into Spark to analyze it. Nested data means some data is inside other data, like boxes inside boxes.
Reading JSON and nested data in Apache Spark
spark.read.json(path)
This reads a JSON file or folder into a Spark DataFrame.
Spark automatically detects nested structures and creates columns for them.
df = spark.read.json("data/simple.json")
df.show()df = spark.read.json("data/nested.json")
df.printSchema()df.select("name", "address.city").show()
This program creates a Spark session, writes sample JSON data with nested fields to a file, reads it back into a DataFrame, and shows the data and schema. It also selects a nested field to demonstrate accessing nested data.
from pyspark.sql import SparkSession spark = SparkSession.builder.appName("ReadJSONExample").getOrCreate() # Sample JSON data with nested structure json_data = [ '{"name": "Alice", "age": 30, "address": {"city": "New York", "zip": "10001"}}', '{"name": "Bob", "age": 25, "address": {"city": "Los Angeles", "zip": "90001"}}' ] # Save sample data to a file with open("sample.json", "w") as f: for line in json_data: f.write(line + "\n") # Read the JSON file df = spark.read.json("sample.json") # Show the data print("DataFrame content:") df.show() # Show the schema to understand nested data print("DataFrame schema:") df.printSchema() # Select nested field print("Selected nested field (address.city):") df.select("name", "address.city").show() spark.stop()
Nested fields are accessed using dot notation like address.city.
Use printSchema() to understand the structure of nested JSON data.
Make sure the JSON file is accessible to Spark (local or distributed file system).
JSON files store data in a structured way, often with nested fields.
Spark can read JSON files directly and handle nested data automatically.
Use dot notation to select nested fields inside the DataFrame.
Practice
Solution
Step 1: Understand Spark JSON reading
Spark reads JSON files and automatically detects nested structures.Step 2: Effect on DataFrame
Nested JSON fields become nested columns accessible via dot notation.Final Answer:
It automatically parses nested fields into a structured DataFrame. -> Option AQuick Check:
Spark JSON reading = automatic nested parsing [OK]
- Thinking Spark ignores nested fields
- Assuming JSON is read as plain text
- Believing manual flattening is always needed
data.json into a Spark DataFrame?Solution
Step 1: Identify correct Spark method for JSON
The method to read JSON files isspark.read.json().Step 2: Check other options
csvreads CSV files,loadis generic but needs format specified,textreads plain text lines.Final Answer:
spark.read.json("data.json") -> Option DQuick Check:
Read JSON file = spark.read.json() [OK]
- Using spark.read.csv() for JSON files
- Using spark.load.json() without format
- Using spark.read.text() for structured JSON
df:
[{"name": "Alice", "info": {"age": 30, "city": "NY"}}, {"name": "Bob", "info": {"age": 25, "city": "LA"}}]
What will be the output of df.select("info.age").collect()?Solution
Step 1: Understand nested field selection
Usingselect("info.age")selects the nested fieldageinsideinfo.Step 2: Result of collect()
collect()returns a list of Row objects with the selected field values.Final Answer:
[Row(age=30), Row(age=25)] -> Option CQuick Check:
Select nested field = list of Rows with that field [OK]
- Expecting plain values instead of Row objects
- Confusing nested field name with top-level
- Selecting wrong nested key
df.select("info-age") but get an error. What is the likely cause?Solution
Step 1: Check syntax for nested field access
Spark uses dot notation likeinfo.age, not dash.Step 2: Understand error cause
Usinginfo-ageis invalid syntax causing an error.Final Answer:
Using a dash (-) instead of dot (.) to access nested fields. -> Option AQuick Check:
Nested field access = dot notation [OK]
- Using dash instead of dot for nested fields
- Assuming nested fields can't be selected
- Ignoring error message details
[{"id": 1, "scores": [10, 20, 30]}, {"id": 2, "scores": [15, 25]}]
How can you transform this DataFrame to have one row per score with columns id and score?Solution
Step 1: Understand array flattening
Theexplode()function creates a new row for each element in the array.Step 2: Apply explode to nested array
Usingdf.select("id", explode("scores").alias("score"))flattens scores into separate rows.Final Answer:
Use df.select("id", explode("scores").alias("score")) to flatten the array. -> Option BQuick Check:
Flatten nested arrays = explode() [OK]
- Not using explode and keeping arrays nested
- Using groupBy() instead of explode()
- Trying to copy arrays without flattening
Ready to prove it?
Pass the test and this pattern moves unknown
