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.
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."
π Table of Contents
Jump to any section β all entries are equal size
π§ 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
jsonmodule. - Step 2: Create a Python dict with sample data.
- Step 3: Call
json.dumps(data)to get a JSON string.
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=2for readable formatting. - Step 2: Pass
sort_keys=Truefor alphabetical keys. - Step 3: Combine both for clean, deterministic output.
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.
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"]))
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 Type | JSON Type |
|---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True / False | true / false |
None | null |
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__}")
π 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.
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.
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.
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))
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
csvmodule. - Step 2: Open a CSV file or use
io.StringIOfor demo data. - Step 3: Create a
csv.readerand iterate over rows.
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)
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.StringIOfor a demo writer. - Step 2: Call
writer.writerow()for each row. - Step 3: Call
.getvalue()to see the CSV output.
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())
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.
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)
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
DictReaderover file-like data. - Step 2: Iterate rows β each is a dict.
- Step 3: Access values by header name.
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
DictWriterwithfieldnames. - Step 2: Call
writeheader()to write the header row. - Step 3: Call
writerow()with dicts.
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.
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.
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().
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)
π 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.
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__)
π‘οΈ 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()intry/except json.JSONDecodeErrorfor user input. - β Use
ensure_ascii=Falseif your data contains non-ASCII characters. - β Remember CSV values are strings β cast numbers and booleans explicitly.
- β Use
DictReader/DictWriterinstead of index-based access for clarity. - β Use
indent=2andsort_keys=Truefor 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.readeron 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
| Aspect | JSON | CSV |
|---|---|---|
| Structure | Nested | Tabular |
| Types | Rich (numbers, bools, null) | Strings only |
| Best for | APIs, configs, complex data | Spreadsheets, exports |
| Human readable | Yes, if indented | Yes, in Excel/Sheets |
| Size | Larger (verbose keys) | Smaller (compact) |
| Tools | Every language, every API | Excel, 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.
"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)