Menu
CoddyTech

Read JSON Lines

Part of the Fundamentals section of Coddy's PySpark journey. Lesson 16 of 18.

Spark’s default JSON reader expects one JSON object per line. This is often called JSON Lines. It is different from one large JSON array. Each object represents a row and its keys name columns.

df = spark.read.schema("city string, visitors int").json(path)

For example, a line {"city": "Oslo", "visitors": 5} becomes one row. A missing field or JSON null becomes a null value under the schema. Providing a schema also makes an empty input readable.

challenge icon

Challenge

Easy

Complete load_data(spark, path). Read JSON Lines with fields item and stock. Return both columns in that order. Keep null stock values as null.

The checker supplies the path; use the path argument. Schema: item string, stock int. The session and F are available. Do not print; the checker reads and displays the result rows.

Try it yourself

def load_data(spark, path):
    return spark.createDataFrame([], 'item string, stock int')
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Python compiler