Bird
Raised Fist0
Apache Sparkdata~20 mins

Reading JSON and nested data in Apache Spark - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
JSON Nested Data Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of reading nested JSON with Spark
What is the output of the following Spark code when reading a nested JSON file and selecting a nested field?
Apache Spark
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('Test').getOrCreate()

json_data = '''[
  {"id": 1, "info": {"name": "Alice", "age": 30}},
  {"id": 2, "info": {"name": "Bob", "age": 25}}
]'''

rdd = spark.sparkContext.parallelize([json_data])
df = spark.read.json(rdd)
df.select('info.name').show()
AAnalysisException: cannot resolve 'info.name' given input columns: [id, info]
B
+----------+
|info.name |
+----------+
|Alice     |
|Bob       |
+----------+
C
+----------+
|info.name |
+----------+
|null      |
|null      |
+----------+
D
+----------+
|name      |
+----------+
|Alice     |
|Bob       |
+----------+
Attempts:
2 left
💡 Hint
Remember how Spark handles nested fields in select statements.
❓ data_output
intermediate
1:30remaining
Count of nested JSON records after flattening
Given a DataFrame loaded from nested JSON, what is the count of rows after flattening the nested array field?
Apache Spark
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode

spark = SparkSession.builder.appName('Test').getOrCreate()

json_data = '''[
  {"id": 1, "items": [{"name": "apple"}, {"name": "banana"}]},
  {"id": 2, "items": [{"name": "orange"}]}
]'''
rdd = spark.sparkContext.parallelize([json_data])
df = spark.read.json(rdd)

flat_df = df.select('id', explode('items').alias('item'))
count = flat_df.count()
A3
B1
C2
D0
Attempts:
2 left
💡 Hint
Count how many total items are in all nested arrays combined.
🔧 Debug
advanced
2:00remaining
Identify the error when reading malformed nested JSON
What error will this Spark code produce when reading a malformed nested JSON string?
Apache Spark
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('Test').getOrCreate()

json_data = '''[
  {"id": 1, "info": {"name": "Alice", "age": 30},
  {"id": 2, "info": {"name": "Bob", "age": 25}}
]'''

rdd = spark.sparkContext.parallelize([json_data])
df = spark.read.json(rdd)
df.show()
AValueError: Expecting ',' delimiter
BAnalysisException: Malformed records are detected in record parsing
CNo error, DataFrame shows both records correctly
DTypeError: 'str' object is not iterable
Attempts:
2 left
💡 Hint
Check the JSON syntax carefully for missing commas or brackets.
🚀 Application
advanced
2:00remaining
Extract nested fields and create new columns
Which code snippet correctly extracts the nested 'age' field from 'info' and creates a new column 'age' in the DataFrame?
Apache Spark
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName('Test').getOrCreate()

json_data = '''[
  {"id": 1, "info": {"name": "Alice", "age": 30}},
  {"id": 2, "info": {"name": "Bob", "age": 25}}
]'''
rdd = spark.sparkContext.parallelize([json_data])
df = spark.read.json(rdd)
Adf.withColumn('age', df['info.age']).show()
Bdf.withColumn('age', df.info['age']).show()
Cdf.withColumn('age', df['info']['age']).show()
Ddf.withColumn('age', df.info.age).show()
Attempts:
2 left
💡 Hint
Use dot notation to access nested fields in Spark DataFrame columns.
🧠 Conceptual
expert
2:30remaining
Understanding schema inference for nested JSON in Spark
When Spark reads a nested JSON file without a predefined schema, what is the behavior of schema inference for nested fields?
ASpark requires a user-defined schema to read nested JSON; otherwise, it raises an error.
BSpark infers only the top-level fields and treats nested fields as strings.
CSpark infers the schema recursively, including all nested fields and their types automatically.
DSpark infers the schema but ignores nested arrays and maps, flattening them into strings.
Attempts:
2 left
💡 Hint
Think about how Spark handles complex JSON structures by default.

Practice

(1/5)
1. What does Apache Spark do when reading a JSON file with nested data?
easy
A. It automatically parses nested fields into a structured DataFrame.
B. It ignores nested fields and reads only top-level data.
C. It converts JSON into plain text without structure.
D. It requires manual flattening before reading nested data.

Solution

  1. Step 1: Understand Spark JSON reading

    Spark reads JSON files and automatically detects nested structures.
  2. Step 2: Effect on DataFrame

    Nested JSON fields become nested columns accessible via dot notation.
  3. Final Answer:

    It automatically parses nested fields into a structured DataFrame. -> Option A
  4. Quick Check:

    Spark JSON reading = automatic nested parsing [OK]
Hint: Spark reads nested JSON as nested columns automatically [OK]
Common Mistakes:
  • Thinking Spark ignores nested fields
  • Assuming JSON is read as plain text
  • Believing manual flattening is always needed
2. Which of the following is the correct syntax to read a JSON file named data.json into a Spark DataFrame?
easy
A. spark.read.text("data.json")
B. spark.read.csv("data.json")
C. spark.load.json("data.json")
D. spark.read.json("data.json")

Solution

  1. Step 1: Identify correct Spark method for JSON

    The method to read JSON files is spark.read.json().
  2. Step 2: Check other options

    csv reads CSV files, load is generic but needs format specified, text reads plain text lines.
  3. Final Answer:

    spark.read.json("data.json") -> Option D
  4. Quick Check:

    Read JSON file = spark.read.json() [OK]
Hint: Use spark.read.json() to load JSON files [OK]
Common Mistakes:
  • Using spark.read.csv() for JSON files
  • Using spark.load.json() without format
  • Using spark.read.text() for structured JSON
3. Given the following JSON data loaded into a DataFrame 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()?
medium
A. [Row(age="NY"), Row(age="LA")]
B. [Row(info=30), Row(info=25)]
C. [Row(age=30), Row(age=25)]
D. [30, 25]

Solution

  1. Step 1: Understand nested field selection

    Using select("info.age") selects the nested field age inside info.
  2. Step 2: Result of collect()

    collect() returns a list of Row objects with the selected field values.
  3. Final Answer:

    [Row(age=30), Row(age=25)] -> Option C
  4. Quick Check:

    Select nested field = list of Rows with that field [OK]
Hint: Selecting nested fields returns Rows with field names [OK]
Common Mistakes:
  • Expecting plain values instead of Row objects
  • Confusing nested field name with top-level
  • Selecting wrong nested key
4. You try to select a nested field using df.select("info-age") but get an error. What is the likely cause?
medium
A. Using a dash (-) instead of dot (.) to access nested fields.
B. The JSON file is empty.
C. The DataFrame was not loaded with spark.read.json().
D. Nested fields cannot be selected in Spark.

Solution

  1. Step 1: Check syntax for nested field access

    Spark uses dot notation like info.age, not dash.
  2. Step 2: Understand error cause

    Using info-age is invalid syntax causing an error.
  3. Final Answer:

    Using a dash (-) instead of dot (.) to access nested fields. -> Option A
  4. Quick Check:

    Nested field access = dot notation [OK]
Hint: Use dot, not dash, to access nested JSON fields [OK]
Common Mistakes:
  • Using dash instead of dot for nested fields
  • Assuming nested fields can't be selected
  • Ignoring error message details
5. You have a JSON file with nested arrays like this:
[{"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?
hard
A. Use df.select("id", "scores") without explode.
B. Use df.select("id", explode("scores").alias("score")) to flatten the array.
C. Use df.groupBy("id").count() to count scores.
D. Use df.withColumn("score", array("scores")) to copy scores.

Solution

  1. Step 1: Understand array flattening

    The explode() function creates a new row for each element in the array.
  2. Step 2: Apply explode to nested array

    Using df.select("id", explode("scores").alias("score")) flattens scores into separate rows.
  3. Final Answer:

    Use df.select("id", explode("scores").alias("score")) to flatten the array. -> Option B
  4. Quick Check:

    Flatten nested arrays = explode() [OK]
Hint: Use explode() to flatten nested arrays into rows [OK]
Common Mistakes:
  • Not using explode and keeping arrays nested
  • Using groupBy() instead of explode()
  • Trying to copy arrays without flattening
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard