Working with JSON and CSV

Python 3.14 · ✓ verified by execution on 2026-07-28

Working with JSON and CSV

In this lesson, we will explore how to handle JSON and CSV data in Python. Let’s start with some core facts verified against the official Python 3.14 documentation.

Fact 1

Claim: The json.dumps() function serializes a Python object to a JSON formatted string.

json.dumps() turns a Python object into a JSON string — that trailing s is the whole difference from dump(), which writes straight to a file.

Example: Serializing a Python dictionary to a JSON string

python
import json
data = {'name': 'Alice', 'age': 30}
json_str = json.dumps(data)
print(json_str)
Output
{"name": "Alice", "age": 30}

Fact 2

Claim: The json.loads() function deserializes a JSON string into a Python object.

json.loads() reads the other direction, parsing a JSON string back into Python dicts and lists. Same rule: loads takes a string, load takes an open file.

Example: Deserializing a JSON string to a Python dictionary

python
import json
json_str = '{"status": "ok", "count": 5}'
data = json.loads(json_str)
print(data['status'])
print(data['count'])
Output
ok
5

Fact 3

Claim: The csv.reader returns an object that iterates over lines in the given CSV file.

csv.reader() hands you an iterator over the rows of a file, each row a list of strings. It handles the awkward parts of CSV — quoted fields, embedded commas — that break naive line.split(',').

Example: Reading delimited data using csv.reader

python
import csv
csv_data = ['a,b,c', '1,2,3', '4,5,6']
reader = csv.reader(csv_data)
for row in reader:
    print(row)
Output
['a', 'b', 'c']
['1', '2', '3']
['4', '5', '6']

Fact 4

Claim: The csv.writer returns an object responsible for converting data into delimited strings.

csv.writer() does the reverse, quoting and escaping fields as needed. Open the file with newline='', or you will get a blank line between every row on Windows.

Example: Writing lists to delimited string using csv.writer

python
import csv
import io
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(['id', 'value'])
writer.writerow([1, 100])
print(output.getvalue(), end='')
Output
id,value
1,100

Fact 5

Claim: The csv.DictReader maps the information in each row to a dictionary.

csv.DictReader is usually the one you want: it reads the header row and gives each subsequent row back as a dict, so you write row['email'] instead of row[3] and stop caring about column order.

Example: Reading CSV rows as dictionaries using csv.DictReader

python
import csv
csv_data = ['name,age', 'Bob,25', 'Charlie,40']
reader = csv.DictReader(csv_data)
for row in reader:
    print(row['name'], row['age'])
Output
Bob 25
Charlie 40

Edge Cases to Consider

Conceptual Overview

Click to view JSON parsing visualizer
python · visualize
import json

# From string to dict (loads)
json_str = '{"a": 1}'
parsed_dict = json.loads(json_str)
print('Parsed:', parsed_dict)

# From dict to string (dumps)
new_str = json.dumps(parsed_dict)
print('Stringified:', new_str)

Check yourself

Which of the following is true regarding: Python dictionaries are exactly the same as JSON objects?

Reveal answer

While similar, JSON requires double quotes for strings and uses true/false/null instead of True/False/None. — While similar, JSON requires double quotes for strings and uses true/false/null instead of True/False/None.

Which of the following is true regarding: jsonload() and json.loads() do the same thing.?

Reveal answer

json.load() reads from a file-like object, whereas json.loads() parses a string. — json.load() reads from a file-like object, whereas json.loads() parses a string.

Which of the following is true regarding: CSV files always use commas as separators?

Reveal answer

CSV stands for Comma-Separated Values, but many 'CSV' files use tabs or semicolons, requiring the 'delimiter' argument in csv.reader. — CSV stands for Comma-Separated Values, but many 'CSV' files use tabs or semicolons, requiring the 'delimiter' argument in csv.reader.

Which of the following is true regarding: You can write a Python set directly to JSON?

Reveal answer

Sets are not JSON serializable by default; they must be converted to lists first. — Sets are not JSON serializable by default; they must be converted to lists first.

Challenges

Challenge 1 +20 XP

Given a JSON string representing a user profile, parse it into a dictionary and print the user's email address.

python
  • Test 1 — expects "zane@example.com\n"
Show solution (0 XP)
import json

profile_json = '{"name": "Zane", "email": "zane@example.com"}'

profile = json.loads(profile_json)
print(profile['email'])

Challenge 2 +20 XP

Write a program that takes a list of usernames and writes them to a CSV string using io.StringIO and csv.writer, with a header 'username'.

python
  • Test 1 — expects "username\r\nAlice\r\nBob\r\n"
Show solution (0 XP)
import csv
import io

users = ['Alice', 'Bob']
output = io.StringIO()

writer = csv.writer(output)
writer.writerow(['username'])
for user in users:
    writer.writerow([user])

print(output.getvalue(), end='')