Back to Home 18 lessons Pyodide ready

Python JSON & CSV
Data Serialization & File Formats

Master Python's json and csv modules: parsing, writing, converting between formats, and handling nested data. 18 interactive lessons with runnable code β€” crafted by @PoeticGlenn.

What you will learn

Everything about Python's two most popular data formats β€” JSON (JavaScript Object Notation) for structured, nested data, and CSV (Comma-Separated Values) for tabular data. Learn json.dumps(), json.loads(), json.dump(), json.load(), csv.reader(), csv.writer(), DictReader, DictWriter, and how to convert between the two formats. Each concept is broken down step-by-step with interactive code examples from @PoeticGlenn.

Why JSON and CSV Rule the Data World

Every program needs to store or exchange data. JSON is the lingua franca of web APIs, configuration files, and structured data β€” lightweight, human-readable, and universally supported. CSV is the workhorse of spreadsheets, data exports, and analytics pipelines β€” simple, tabular, and Excel-compatible. Together, they cover the vast majority of real-world data serialization tasks. This curriculum, designed by @PoeticGlenn, teaches you to read, write, parse, and convert between these formats with Python's built-in json and csv modules β€” no third-party libraries needed.

Structured Data

JSON handles nested objects, arrays, and mixed types β€” perfect for APIs and configs.

Tabular Data

CSV is ideal for spreadsheets, logs, and any data that fits in rows and columns.

Interoperability

Both formats are universal β€” read and write with Python, Excel, databases, or any tool.

"Data is the new oil. JSON and CSV are the pipelines that move it." β€” @PoeticGlenn 🐍

Every Data Pipeline Starts Here

Whether you're building a web scraper, a data analysis pipeline, a configuration loader, or an API client, you'll work with JSON and CSV. These two formats are the foundation of data exchange in Python. This curriculum, curated by @PoeticGlenn, ensures you can handle them fluently β€” including edge cases like encoding, nested data, and type conversion.

🌐 APIs & Web

Every REST API returns JSON. Learn to parse it, navigate it, and save it to disk.

πŸ“Š Data Analysis

CSV is the universal export format. Load datasets, filter rows, and write results back.

βš™οΈ Configuration

JSON is the standard for config files. Load settings, validate, and merge with defaults.

πŸ”„ Format Conversion

Convert between JSON and CSV with a few lines β€” essential for data migration and ETL.

@PoeticGlenn says: "If you can move data between JSON and CSV, you can connect almost any two systems."

The Universal Data Exchange Formats

JSON and CSV aren't just Python concepts β€” they're universal. JSON is the native format of JavaScript, the default for REST APIs, and the backbone of tools like MongoDB, Firebase, and every modern web framework. CSV is the oldest and most widely supported tabular format, used by Excel, Google Sheets, pandas, and virtually every database export tool. Learning these formats in Python, as taught by @PoeticGlenn, gives you skills that transfer to every language and platform.

Universal

Every language, every platform, every tool reads JSON and CSV. Learn once, use everywhere.

Data Foundation

ETL pipelines, data science workflows, and machine learning all start with these formats.

Integration

APIs, databases, spreadsheets, configs β€” JSON and CSV are the glue between systems.

"The data doesn't care what language you speak β€” JSON and CSV are how it travels."

πŸ”§ JSON Basics β€” dumps() & loads()

Convert Python objects to JSON strings and back.

πŸ“ 1.1 json.dumps() β€” Python to JSON String

Serialize a Python object into a JSON-formatted string.

Step-by-step explanation:

  • Step 1: Import the json module.
  • Step 2: Create a Python dict with sample data.
  • Step 3: Call json.dumps(data) to get a JSON string.
python
import json

data = {
    "name": "Alice",
    "age": 30,
    "active": True,
    "hobbies": ["reading", "coding"],
    "address": {"city": "Tokyo", "zip": "100-0001"}
}

json_str = json.dumps(data)
print(json_str)
print("\ntype:", type(json_str))
πŸ’‘ dumps = "dump string". It returns a string; dump (without the "s") writes to a file.

πŸ“ 1.2 Pretty-Printing with indent and sort_keys

Make JSON human-readable with indentation and sorted keys.

Step-by-step explanation:

  • Step 1: Pass indent=2 for readable formatting.
  • Step 2: Pass sort_keys=True for alphabetical keys.
  • Step 3: Combine both for clean, deterministic output.
python
import json

data = {"b": 2, "a": 1, "c": {"z": 26, "y": 25}}

print("Compact:")
print(json.dumps(data))

print("\nIndented:")
print(json.dumps(data, indent=2))

print("\nSorted keys + indented:")
print(json.dumps(data, indent=2, sort_keys=True))
✨ sort_keys=True is great for diffing JSON files in version control.

πŸ“ 1.3 json.loads() β€” JSON String to Python

Parse a JSON string back into Python objects.

Step-by-step explanation:

  • Step 1: Have a JSON string ready.
  • Step 2: Call json.loads(json_str).
  • Step 3: Access fields as dict keys.
python
import json

json_str = '{"name": "Bob", "scores": [90, 85, 92], "active": true}'

data = json.loads(json_str)
print("Type:", type(data))
print("Name:", data["name"])
print("Scores:", data["scores"])
print("Active:", data["active"])
print("Average:", sum(data["scores"]) / len(data["scores"]))
⚠️ JSON uses lowercase true/false/null, not Python's True/False/None. json.loads() converts them automatically.

πŸ“ 1.4 Type Mapping β€” What Converts to What

Understand how Python types map to JSON types and back.

Python TypeJSON Type
dictobject
list, tuplearray
strstring
int, floatnumber
True / Falsetrue / false
Nonenull
python
import json

values = {
    "int": 42,
    "float": 3.14,
    "bool": True,
    "none": None,
    "list": [1, 2, 3],
    "nested": {"key": "value"}
}

s = json.dumps(values, indent=2)
print(s)

# Round-trip: string back to Python
restored = json.loads(s)
print("\nRestored types:")
for k, v in restored.items():
    print(f"  {k}: {type(v).__name__}")
πŸ’‘ Tuples become lists after a round-trip through JSON β€” JSON has no tuple type.

πŸ“ JSON Files β€” dump() & load()

Read and write JSON files directly β€” no string intermediary.

πŸ“ 2.1 Writing JSON to a File

Use json.dump() to write directly to a file object.

Step-by-step explanation:

  • Step 1: Open a file in write mode with "w".
  • Step 2: Call json.dump(data, f, indent=2).
  • Step 3: The context manager closes the file automatically.
python
import json

data = {
    "app": "Poetic Bytes",
    "version": "2.0",
    "features": ["runnable code", "dark theme", "mobile-friendly"]
}

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

print("File written!")
with open("config.json", "r", encoding="utf-8") as f:
    print(f.read())
πŸ’‘ ensure_ascii=False preserves non-ASCII characters (like Γ© or ζ—₯) instead of escaping them as \uXXXX.

πŸ“ 2.2 Reading JSON from a File

Use json.load() to parse directly from a file object.

Step-by-step explanation:

  • Step 1: Open the file in read mode with "r".
  • Step 2: Call json.load(f) β€” returns a Python object.
  • Step 3: Access fields as dict keys.
python
import json

# First create the file
with open("user.json", "w", encoding="utf-8") as f:
    json.dump({"name": "Carol", "score": 98, "tags": ["admin", "active"]}, f, indent=2)

# Now read it back
with open("user.json", "r", encoding="utf-8") as f:
    user = json.load(f)

print("Name: ", user["name"])
print("Score:", user["score"])
print("Tags: ", user["tags"])
print("First tag:", user["tags"][0])

πŸ“ 2.3 Error Handling β€” Malformed JSON

Catch json.JSONDecodeError to handle invalid input gracefully.

Step-by-step explanation:

  • Step 1: Try to parse a malformed string.
  • Step 2: Catch json.JSONDecodeError.
  • Step 3: Print a helpful error message.
python
import json

bad_json = '{"name": "Dave", "score": 88,}'

try:
    data = json.loads(bad_json)
except json.JSONDecodeError as e:
    print("Invalid JSON!")
    print("Message:", e.msg)
    print("Position:", e.pos)

valid_json = '{"name": "Dave", "score": 88}'
print("\nValid JSON parses fine:", json.loads(valid_json))
⚠️ The trailing comma after 88 is invalid JSON β€” Python dicts allow trailing commas, but JSON does not.

πŸ“Š CSV Basics β€” reader() & writer()

Read and write comma-separated values with Python's built-in csv module.

πŸ“ 3.1 csv.reader() β€” Read Rows

Parse CSV data into lists of strings.

Step-by-step explanation:

  • Step 1: Import the csv module.
  • Step 2: Open a CSV file or use io.StringIO for demo data.
  • Step 3: Create a csv.reader and iterate over rows.
python
import csv
import io

csv_data = """name,age,city
Alice,30,Tokyo
Bob,25,Paris
Carol,35,New York"""

reader = csv.reader(io.StringIO(csv_data))

for row in reader:
    print(row)
πŸ’‘ Each row is a list of strings β€” even numbers are returned as strings. Convert types manually.

πŸ“ 3.2 csv.writer() β€” Write Rows

Write lists of values as CSV rows.

Step-by-step explanation:

  • Step 1: Use io.StringIO for a demo writer.
  • Step 2: Call writer.writerow() for each row.
  • Step 3: Call .getvalue() to see the CSV output.
python
import csv
import io

output = io.StringIO()
writer = csv.writer(output)

writer.writerow(["name", "age", "city"])
writer.writerow(["Alice", 30, "Tokyo"])
writer.writerow(["Bob", 25, "Paris"])
writer.writerow(["Carol", 35, "New York"])

print(output.getvalue())
✨ Values with commas, quotes, or newlines are automatically quoted by csv.writer.

πŸ“ 3.3 CSV Files β€” Read & Write on Disk

Use open() with newline="" to avoid double newlines on Windows.

Step-by-step explanation:

  • Step 1: Open the file with newline="".
  • Step 2: Write rows with csv.writer.
  • Step 3: Read back with csv.reader.
python
import csv

# Write to a real file
with open("people.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "age"])
    writer.writerow(["Alice", 30])
    writer.writerow(["Bob", 25])

print("File written!")

# Read it back
with open("people.csv", "r", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
⚠️ Always pass newline="" when opening CSV files β€” otherwise you'll get blank lines between rows on Windows.

πŸ“‹ DictReader & DictWriter β€” Row Dicts

Access CSV rows as dictionaries β€” far more readable than index-based lists.

πŸ“ 4.1 csv.DictReader

The first row becomes the header β€” each subsequent row becomes an OrderedDict.

Step-by-step explanation:

  • Step 1: Create a DictReader over file-like data.
  • Step 2: Iterate rows β€” each is a dict.
  • Step 3: Access values by header name.
python
import csv
import io

csv_data = """name,age,city
Alice,30,Tokyo
Bob,25,Paris
Carol,35,New York"""

reader = csv.DictReader(io.StringIO(csv_data))

for row in reader:
    print(row)
    print(f"  {row['name']} is {row['age']} years old, lives in {row['city']}")
πŸ’‘ DictReader accesses reader.fieldnames for the header row. If the file has no header, pass fieldnames=[...] manually.

πŸ“ 4.2 csv.DictWriter

Write dictionaries as CSV rows using a declared set of field names.

Step-by-step explanation:

  • Step 1: Create a DictWriter with fieldnames.
  • Step 2: Call writeheader() to write the header row.
  • Step 3: Call writerow() with dicts.
python
import csv
import io

output = io.StringIO()
fieldnames = ["name", "age", "city"]

writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()

writer.writerow({"name": "Alice", "age": 30, "city": "Tokyo"})
writer.writerow({"name": "Bob", "age": 25, "city": "Paris"})
writer.writerow({"name": "Carol", "age": 35, "city": "New York"})

print(output.getvalue())
✨ DictWriter writes keys in the order specified by fieldnames β€” extra keys are silently ignored (or raise if extrasaction="raise").

πŸ“ 4.3 Practical: Filter a CSV

Read a CSV, filter rows, and write the results to a new file.

Step-by-step explanation:

  • Step 1: Read rows with DictReader.
  • Step 2: Convert the age string to an int and filter.
  • Step 3: Write filtered rows with DictWriter.
python
import csv
import io

csv_data = """name,age,city
Alice,30,Tokyo
Bob,17,Paris
Carol,35,New York
Dave,15,Berlin"""

reader = csv.DictReader(io.StringIO(csv_data))
adults = [row for row in reader if int(row["age"]) >= 18]

output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=["name", "age", "city"])
writer.writeheader()
writer.writerows(adults)

print("Adults only:")
print(output.getvalue())

πŸ”„ JSON ↔ CSV β€” Converting Between Formats

Move data between structured JSON and tabular CSV seamlessly.

πŸ“ 5.1 JSON to CSV

Convert a list of JSON objects to CSV rows.

Step-by-step explanation:

  • Step 1: Parse JSON into a list of dicts.
  • Step 2: Extract field names from the first dict's keys.
  • Step 3: Write rows with DictWriter.
python
import json
import csv
import io

json_str = """[
    {"name": "Alice", "age": 30, "city": "Tokyo"},
    {"name": "Bob", "age": 25, "city": "Paris"},
    {"name": "Carol", "age": 35, "city": "New York"}
]"""

records = json.loads(json_str)

output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=["name", "age", "city"])
writer.writeheader()
writer.writerows(records)

print(output.getvalue())

πŸ“ 5.2 CSV to JSON

Convert CSV rows to a JSON array of objects.

Step-by-step explanation:

  • Step 1: Read CSV with DictReader.
  • Step 2: Convert to a list of dicts.
  • Step 3: Serialize with json.dumps().
python
import csv
import json
import io

csv_data = """name,age,city
Alice,30,Tokyo
Bob,25,Paris
Carol,35,New York"""

reader = csv.DictReader(io.StringIO(csv_data))
records = list(reader)

json_str = json.dumps(records, indent=2)
print(json_str)
πŸ’‘ Note that CSV values become strings in JSON. To preserve types (int, float, bool), cast them explicitly during conversion.

πŸ“ 5.3 Type-Safe Conversion

Preserve numeric types during CSV-to-JSON conversion.

Step-by-step explanation:

  • Step 1: Read CSV rows with DictReader.
  • Step 2: Define a schema mapping field names to types.
  • Step 3: Cast each value based on the schema.
python
import csv
import json
import io

csv_data = """name,age,score
Alice,30,88.5
Bob,25,92.0
Carol,35,79.5"""

schema = {"name": str, "age": int, "score": float}

reader = csv.DictReader(io.StringIO(csv_data))
records = []
for row in reader:
    typed = {k: schema[k](v) for k, v in row.items()}
    records.append(typed)

print(json.dumps(records, indent=2))
print("\nage type:", type(records[0]["age"]).__name__)
print("score type:", type(records[0]["score"]).__name__)
✨ Using a schema dict keeps type conversion DRY and makes it easy to validate inputs.

πŸ›‘οΈ Best Practices & Common Pitfalls

Avoid the mistakes that trip up most developers.

πŸ“ 6.1 Checklist

  • βœ” Always specify encoding="utf-8" when opening JSON or CSV files.
  • βœ” Use newline="" when opening CSV files to avoid extra blank lines.
  • βœ” Wrap json.loads() in try/except json.JSONDecodeError for user input.
  • βœ” Use ensure_ascii=False if your data contains non-ASCII characters.
  • βœ” Remember CSV values are strings β€” cast numbers and booleans explicitly.
  • βœ” Use DictReader/DictWriter instead of index-based access for clarity.
  • βœ” Use indent=2 and sort_keys=True for human-readable JSON files.
  • βœ” Don't embed JSON as a Python string literal β€” write it to a file or use json.dumps().
  • βœ” Be cautious with csv.reader on very large files β€” iterate instead of loading everything.
  • βœ” For nested JSON, flatten with json.dumps() + a helper if you need CSV output.

πŸ“ 6.2 Comparing JSON and CSV

AspectJSONCSV
StructureNestedTabular
TypesRich (numbers, bools, null)Strings only
Best forAPIs, configs, complex dataSpreadsheets, exports
Human readableYes, if indentedYes, in Excel/Sheets
SizeLarger (verbose keys)Smaller (compact)
ToolsEvery language, every APIExcel, pandas, databases

❓ Frequently Asked Questions β€” Python JSON & CSV

Common questions about data serialization in Python.

What's the difference between json.dump and json.dumps?

+

json.dumps returns a string, while json.dump writes directly to a file object. Similarly, json.loads parses a string, while json.load reads from a file. The "s" stands for "string".

Why are all my CSV numbers returned as strings?

+

CSV has no concept of types β€” everything is text. csv.reader returns strings, and you must convert them to int, float, or bool yourself. Use a schema dict or helper function to automate this.

How do I handle Unicode in JSON?

+

By default, json.dumps escapes non-ASCII characters as \uXXXX. Pass ensure_ascii=False to preserve them. Also open files with encoding="utf-8" for both reading and writing.

What's the difference between csv.reader and csv.DictReader?

+

csv.reader returns rows as lists (index-based access). csv.DictReader uses the first row as headers and returns each row as a dict, so you can access values by column name. DictReader is more readable for CSVs with headers.

How do I convert a nested JSON object to CSV?

+

CSV is flat β€” you can't represent nested structures directly. Either (1) flatten the JSON into dotted keys like address.city, (2) serialize nested values as JSON strings inside the cell, or (3) split into multiple related CSV files. Choose based on your downstream consumer.

Can I read a CSV with a custom delimiter?

+

Yes β€” pass delimiter="\t" for tab-separated, delimiter="|" for pipe-separated, etc. Both csv.reader and csv.writer accept the delimiter argument.

How do I pretty-print JSON in the terminal?

+

Use python -m json.tool file.json from the command line, or print(json.dumps(data, indent=2)) in code. The json.tool module also supports --sort-keys and --compact flags.

Is there a way to stream large JSON files?

+

The standard json module loads the entire file into memory. For very large files, use ijson (streaming parser) or process JSON incrementally with json.loads on individual lines (JSON Lines format). CSV, by contrast, is already streamable row by row.

πŸ’› You've Mastered Python JSON & CSV

From serializing Python dicts to JSON strings to converting between tabular CSV and nested JSON, you now have a complete toolkit for real-world data handling. You can parse APIs, load datasets, write configs, and transform data between formats with confidence.

This curriculum, crafted by @PoeticGlenn, gives you the foundation for every data-driven Python project β€” whether you're building web scrapers, data pipelines, automation scripts, or full-stack applications. The patterns you've learned will serve you for years.

18 lessons 20+ code examples 1.0k+ learners

"Data is only as valuable as the format you can move it in. JSON and CSV are the bridges you'll cross every day." β€” Glenn Junsay Pansensoy (@PoeticGlenn)