Browse Python Topics ▼
Pick a Web Framework

Working with JSON and CSV Data

📂 Files & Operating System 📘 Lesson 31 of 57

Serialize, parse, and exchange structured data in Python using the standard library json and csv modules, including DictReader and DictWriter.

When your Python code stores user records in a dictionary or product listings in a list, that data is formatted specifically for Python’s internal memory.

What happens when your Python application needs to send that data to:

  • A web browser running JavaScript?
  • An accountant opening numbers in Microsoft Excel or Google Sheets?
  • A mobile app built in Swift or Kotlin?

None of those external systems understand raw Python memory. To communicate across different programming languages and software tools, we serialize our data into universal, human-readable text formats:

  1. JSON (JavaScript Object Notation): The undisputed standard format for web APIs, configuration files, and cloud services.
  2. CSV (Comma-Separated Values): The global standard for tabular, spreadsheet, and data science workflows.

Python includes powerful standard library modules for both: json and csv.


1. Mastering JSON in Python

JSON represents data as nested key-value objects and arrays. Python maps JSON types to native Python types effortlessly:

JSON TypePython Equivalent Type
object ({ "k": "v" })dict ({ "k": "v" })
array ([1, 2, 3])list ([1, 2, 3])
string ("hello")str ("hello")
number (42, 3.14)int, float
true / falseTrue / False
nullNone

The “S” Rule: String vs Stream

Python provides four primary functions in the json module. Remembering the meaning of the letter s makes them unforgettable:

  • json.dumps() / json.loads(): The s stands for string. These operate on text strings in memory.
  • json.dump() / json.load(): No “s”. These read and write directly to an open file stream.

In-Memory JSON: dumps() and loads()

import json

# Python dictionary
user_profile = {
    "username": "alex_dev",
    "id": 8492,
    "is_premium": True,
    "skills": ["Python", "FastAPI", "PostgreSQL"],
    "bio": None
}

# 1. SERIALIZE: Python dict -> JSON string
json_text = json.dumps(user_profile, indent=2)
print("JSON string format:\n", json_text)

# 2. DESERIALIZE: JSON string -> Python dict
parsed_data = json.loads(json_text)
print("\nExtracted username:", parsed_data["username"])
print("Premium status:", parsed_data["is_premium"])  # Native Python boolean True!

Output:

JSON string format:
 {
  "username": "alex_dev",
  "id": 8492,
  "is_premium": true,
  "skills": [
    "Python",
    "FastAPI",
    "PostgreSQL"
  ],
  "bio": null
}

Extracted username: alex_dev
Premium status: True

Notice how true became True and null became None automatically!


File-Based JSON: dump() and load()

When saving to or reading from a file, pass the open file object directly using with open(...):

import json

app_settings = {"theme": "dark", "volume": 80, "notifications": True}

# Save directly to disk file:
with open("config.json", "w", encoding="utf-8") as f:
    json.dump(app_settings, f, indent=4)

# Load directly from disk file:
with open("config.json", "r", encoding="utf-8") as f:
    loaded_settings = json.load(f)

print("Restored theme setting:", loaded_settings["theme"])  # dark

2. Mastering CSV in Python

A CSV file represents tabular data where every line is a row, and columns are separated by commas.

The Rookie Trap: Why Never Use line.split(",")

Beginners often attempt to parse CSV files manually with string splitting:

# DANGEROUS: Do not parse CSV manually!
row = 'John,Doe,"San Francisco, CA",32'
parts = row.split(",")
print(parts)  # ['John', 'Doe', '"San Francisco', ' CA"', '32'] -> Corrupted columns!

Because "San Francisco, CA" contains an internal comma, manual string splitting broke the city and state into two invalid columns!

Python’s built-in csv module handles quotes, escaping, and commas with complete accuracy.


The Professional Tool: csv.DictReader

Rather than dealing with cryptic numerical indices (row[0], row[1]), csv.DictReader reads the very first line as column headers and yields each subsequent row as a clean Python dictionary:

import csv

# Simulated CSV content
csv_data = """Name,Department,Salary
Alice Smith,Engineering,95000
Bob Jones,Marketing,78000
Charlie Brown,Design,82000"""

# Write temporary CSV file
with open("employees.csv", "w", encoding="utf-8") as f:
    f.write(csv_data)

# Read using DictReader
with open("employees.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        # Access columns by their header name!
        print(f"{row['Name']} works in {row['Department']} (Salary: ${row['Salary']})")

Output:

Alice Smith works in Engineering (Salary: $95000)
Bob Jones works in Marketing (Salary: $78000)
Charlie Brown works in Design (Salary: $82000)

Writing CSV Files with csv.DictWriter

When writing tabular records, csv.DictWriter ensures headers and columns align perfectly:

import csv

products = [
    {"sku": "A101", "name": "Wireless Mouse", "price": 24.99},
    {"sku": "B202", "name": "Mechanical Keyboard", "price": 89.95},
    {"sku": "C303", "name": "USB-C Hub", "price": 45.00}
]

fields = ["sku", "name", "price"]

with open("catalog.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=fields)
    
    # 1. Write the top header row
    writer.writeheader()
    
    # 2. Write all data rows
    writer.writerows(products)

print("Catalog CSV successfully written to disk!")

[!NOTE] Always pass newline="" when opening files for writing with Python’s csv module. This prevents empty blank lines from appearing between rows on Windows systems.


Summary & What’s Next

  • Use JSON for nested records, APIs, and hierarchical data.
  • Remember the S Rule: dumps/loads work with strings; dump/load work with file streams.
  • Never split CSV files manually with .split(","). Always use Python’s csv module.
  • Use csv.DictReader and csv.DictWriter to process spreadsheet data using descriptive column names.

Now that you know how to read and write both plain and structured files, discover how to navigate folders, locate files, and build cross-platform file paths using pathlib.

Test your understanding of Working with JSON and CSV Data

Quick interactive practice questions with instant feedback.

Take Quiz →