Skip to content
PythonData, APIs, and Concurrencybeginner30 min read

JSON and CSV Data

Read, write, validate, and transform JSON and CSV data using Python's standard library.

In this lesson, you will learn

  • ✓Explain when JSON and CSV are appropriate for storing structured data.
  • ✓Distinguish json.loads(), json.load(), json.dumps(), and json.dump().
  • ✓Read and write CSV rows using reader, writer, DictReader, and DictWriter.
  • ✓Understand how JSON types differ from CSV's usual string-based values.
  • ✓Handle missing files, missing dictionary keys, and malformed JSON.
  • ✓Use UTF-8 encoding, context managers, and newline handling correctly.
  • ✓Choose an appropriate format for a given data-storage task.

1. Understand JSON and CSV

JSON stands for JavaScript Object Notation. Despite its name, it is a language-independent data-interchange format. It represents objects, arrays, strings, numbers, booleans, and null values.

CSV stands for Comma-Separated Values. It represents tabular data using records and fields. The first row often contains column names, followed by rows of data.

Choose JSON when data contains nested objects, arrays, settings, or API responses. Choose CSV when the data is naturally a table with consistent columns.

Neither format automatically validates your application's business rules. A file can be valid JSON or CSV and still contain missing fields, unexpected values, or invalid data.

Example JSON data

Example JSON data
json
{
"name": "Asha",
"age": 22,
"active": true,
"skills": ["Python", "SQL"],
"address": {
"city": "Lucknow"
}
}

The outer object contains named properties. age is a number and active is a boolean. skills is an array of strings. address is a nested object. JSON uses double quotes for strings and property names. Python's True, False, and None spellings are not valid JSON literals.

2. Python values and JSON values

The json module converts between compatible Python objects and JSON text. This process is called serialization when Python data becomes JSON text, and deserialization when JSON text becomes Python data.

Python dictionaries usually correspond to JSON objects, lists correspond to JSON arrays, strings correspond to JSON strings, and booleans correspond to JSON booleans. Python None corresponds to JSON null.

JSON object property names are strings. Converting a Python dictionary with non-string keys to JSON may change those keys when the data is decoded again, so prefer string keys for JSON objects.

Convert JSON text into Python data

Convert JSON text into Python data
python
import json
 
text = '{"name": "Asha", "age": 22, "active": true}'
data = json.loads(text)
 
print(data['name'])
print(data['age'])
print(data['active'])
Output
Asha 22 True

json.loads() parses a JSON string and returns the corresponding Python object. data is a Python dictionary. The JSON number 22 becomes a Python integer. The JSON literal true becomes Python's True. The quotes surrounding the JSON document are Python string delimiters; the content inside must follow JSON syntax.

Note

JSON has no native representation for every Python type. For example, sets, file objects, and custom class instances need an explicit conversion strategy before they can be serialized.

3. The four essential JSON functions

Remember the difference between the s suffix and the file-based functions. loads() reads JSON from a string, load() reads JSON from a file-like object, dumps() creates a JSON string, and dump() writes JSON to a file-like object.

These functions are related, but they are not interchangeable. Choosing the wrong one is a common cause of errors.

Quick reference

Quick reference
text
json.loads(text) # JSON string -> Python object
json.load(file) # JSON file -> Python object
json.dumps(data) # Python object -> JSON string
json.dump(data, file) # Python object -> JSON file

loads and dumps operate on strings. load and dump operate on file-like objects. The functions return different results: dump() writes to the supplied file and returns None.

4. Read and write JSON files

For file operations, use open() with a with statement. The with statement ensures the file is closed when the block ends, including when an exception occurs.

Use encoding='utf-8' when reading and writing ordinary text-based JSON files. UTF-8 is a common interoperable encoding for JSON data.

Use json.load(file) to read a JSON document and json.dump(data, file) to write one. The examples below use a file named student.json in the current working directory.

Write student.json

Write student.json
python
import json
 
student = {
'name': 'Asha',
'age': 22,
'skills': ['Python', 'SQL']
}
 
with open('student.json', 'w', encoding='utf-8') as file:
json.dump(student, file, indent=2)
 
print('JSON saved')
Output
JSON saved

The w mode creates the file or truncates an existing file. json.dump() serializes student and writes the JSON text to file. indent=2 makes the stored document easier to inspect. The message confirms that execution reached the print statement; it is not a substitute for checking the file when data integrity matters.

Caution

Opening a file in write mode can erase its existing contents. Use it intentionally, and avoid overwriting important data before validating the replacement.

5. JSON errors and missing values

A JSON document can be malformed. For example, Python-style single-quoted property names and trailing commas are not valid JSON syntax. json.loads() and json.load() raise json.JSONDecodeError when the document cannot be parsed.

A valid JSON object can also lack a key your program expects. Accessing a missing dictionary key with square brackets raises KeyError. Use get() when a missing key should have a default value, or validate required fields explicitly.

File access can fail independently of JSON parsing. FileNotFoundError means the path could not be found, while PermissionError indicates that access was denied. Catch exceptions when you can respond meaningfully, rather than hiding every error.

Handle invalid JSON text

Handle invalid JSON text
python
import json
 
text = '{"age": 22,}'
 
try:
data = json.loads(text)
except json.JSONDecodeError:
print('Invalid JSON')
Output
Invalid JSON

The trailing comma makes this JSON document invalid. json.loads() raises JSONDecodeError. The except block handles that specific parsing error and displays a useful message.

Note

A default value is appropriate only when the field is genuinely optional. For required fields, validate the input and report the missing field rather than silently accepting incomplete data.

6. Read CSV with csv.reader

The csv module handles quoting, delimiters, and records more reliably than manually splitting text on commas. A field can itself contain a comma, so line.split(',') is not a general CSV parser.

csv.reader() returns rows as lists of strings. If the file has a header row, you can read it separately or use DictReader to work with column names.

When opening a CSV file, use newline='' so the csv module can handle newline conventions correctly. Specify encoding='utf-8' when that matches the file's encoding.

Read rows from an in-memory CSV example

Read rows from an in-memory CSV example
python
import csv
from io import StringIO
 
text = 'name,age\nAsha,22\nRavi,24\n'
reader = csv.reader(StringIO(text))
 
for row in reader:
print(row)
Output
['name', 'age'] ['Asha', '22'] ['Ravi', '24']

StringIO provides a file-like object containing the sample text, so the example needs no external file. Each row is returned as a list. The first row is the header, but csv.reader does not automatically treat it specially. The age values are strings, not integers.

7. Read CSV using csv.DictReader

DictReader maps each row to a dictionary using the column names from the header row by default. This often makes code easier to read because you can refer to fields by name rather than remembering column indexes.

The row values are still normally strings. Convert numeric fields explicitly before doing arithmetic, and validate them when the input may be unreliable.

If a row is missing a value or contains unexpected extra fields, decide how your application should handle that situation instead of assuming every record is perfect.

Read records by column name

Read records by column name
python
import csv
from io import StringIO
 
text = 'name,age\nAsha,22\nRavi,24\n'
reader = csv.DictReader(StringIO(text))
 
for row in reader:
print(row['name'], int(row['age']))
Output
Asha 22 Ravi 24

DictReader uses name and age as dictionary keys. row['name'] retrieves the name string. int(row['age']) converts the age string to an integer. int() raises ValueError if the field contains a value such as unknown rather than a valid integer.

8. Write CSV using writer and DictWriter

Use csv.writer() when you want to write rows as sequences, such as lists or tuples. Use writerow() for one record and writerows() for multiple records.

Use csv.DictWriter() when your records are dictionaries. You must provide fieldnames, which define the column order. Call writeheader() if you want a header row.

When writing a CSV file, use open(..., 'w', newline='', encoding='utf-8'). Opening with w replaces an existing file, so be careful when the file contains important data.

Write rows using csv.writer

Write rows using csv.writer
python
import csv
from io import StringIO
 
buffer = StringIO(newline='')
writer = csv.writer(buffer)
writer.writerow(['name', 'age'])
writer.writerow(['Asha', 22])
 
print(buffer.getvalue(), end='')
Output
name,age Asha,22

StringIO captures output in memory for this example. writerow() accepts a sequence of field values. The writer handles the CSV record formatting. The final print uses end='' because the generated CSV text already ends with a record terminator.

9. JSON versus CSV: choose the right format

JSON is a strong fit for nested records, application settings, and API messages. CSV is a strong fit for rectangular datasets that people may inspect or process using spreadsheet software.

CSV does not inherently preserve data types. When a reader returns the string '22', your application must decide whether it represents an integer, an identifier, or text. Converting every digit-only field automatically can be incorrect for values such as postal codes or IDs with leading zeros.

JSON preserves common distinctions such as numbers, strings, booleans, arrays, objects, and null. It still does not preserve every Python-specific type or guarantee that the data meets your application's schema.

CSV and JSON can both represent collections of records, but they have different strengths. Use the format that matches the structure and consumers of the data.

The same records in two formats

The same records in two formats
text
JSON:
[
{"name": "Asha", "age": 22},
{"name": "Ravi", "age": 24}
]
 
CSV:
name,age
Asha,22
Ravi,24

The JSON representation is an array containing two objects. The CSV representation is a table with two columns and two data rows. JSON naturally represents nested data, while CSV is more natural for consistently shaped rows and columns.

10. Common errors and safe handling

Data files are external inputs and should not be trusted blindly. A file can be missing, malformed, empty, or different from the structure your program expects.

Catch the specific exceptions your application can handle meaningfully. For JSON parsing, use JSONDecodeError. For missing files, use FileNotFoundError. For numeric conversions, consider ValueError. CSV parsing can raise csv.Error for relevant parsing failures.

Do not use a broad except block that silently ignores every failure. It can hide programming errors and leave the application working with incomplete data.

For production applications, validate required columns, field types, allowed ranges, and record counts before relying on imported data.

Handle a missing JSON file

Handle a missing JSON file
python
import json
 
try:
with open('missing.json', 'r', encoding='utf-8') as file:
data = json.load(file)
except FileNotFoundError:
print('File not found')
Output
File not found

Assuming missing.json does not exist in the current working directory, open() raises FileNotFoundError. The except block handles that particular failure. Other errors, such as malformed JSON in an existing file, are not caught by this block.

Caution

Do not assume that syntactically valid input is safe or correct. Validate values before using them in calculations, database operations, or application decisions.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Using json.loads() to read a file object.

Why it happens: json.loads() parses a string containing JSON, while json.load() reads JSON data from a file-like object.

Incorrect Approach
script.py
python
Using json.loads() to read a file object.
Correct Solution
script.py
python
Use json.load(file) for a file-like object and json.loads(text) for a JSON string.

Key takeaway: Use json.load(file) for a file-like object and json.loads(text) for a JSON string.

#2 Using json.dump() when you only want a JSON string.

Why it happens: json.dump() writes JSON to a file-like object; json.dumps() returns the serialized JSON text as a string.

Incorrect Approach
script.py
python
Using json.dump() when you only want a JSON string.
Correct Solution
script.py
python
Use json.dumps(data) to produce a string. Use json.dump(data, file) to write to a file.

Key takeaway: Use json.dumps(data) to produce a string. Use json.dump(data, file) to write to a file.

#3 Using Python literals directly in JSON.

Why it happens: JSON uses its own syntax, including true, false, and null, and does not accept Python-specific literals such as True, False, or None.

Incorrect Approach
script.py
python
Using Python literals directly in JSON.
Correct Solution
script.py
python
JSON uses true, false, and null, whereas Python uses True, False, and None. Use json.dumps() to serialize compatible Python values correctly.

Key takeaway: JSON uses true, false, and null, whereas Python uses True, False, and None. Use json.dumps() to serialize compatible Python values correctly.

#4 Splitting CSV rows manually with split(',').

Why it happens: CSV fields can contain quoted commas, escaped quotes, or embedded newlines, so manual split(',') parsing breaks valid CSV data.

Incorrect Approach
script.py
python
Splitting CSV rows manually with split(',').
Correct Solution
script.py
python
Use csv.reader() or csv.DictReader() because valid CSV fields can contain quoted commas and newlines.

Key takeaway: Use csv.reader() or csv.DictReader() because valid CSV fields can contain quoted commas and newlines.

#5 Assuming CSV numbers are automatically integers.

Why it happens: CSV readers return text fields by default; convert numeric columns explicitly and handle invalid values.

Incorrect Approach
script.py
python
Assuming CSV numbers are automatically integers.
Correct Solution
script.py
python
Convert values explicitly and handle invalid input. A CSV reader normally returns field values as strings.

Key takeaway: Convert values explicitly and handle invalid input. A CSV reader normally returns field values as strings.

#6 Opening CSV files without newline=''.

Why it happens: Opening CSV files with newline='' lets the csv module handle newline conventions correctly and helps avoid extra blank lines on some platforms.

Incorrect Approach
script.py
python
Opening CSV files without newline=''.
Correct Solution
script.py
python
Use newline='' when opening CSV files so the csv module can handle line endings correctly.

Key takeaway: Use newline='' when opening CSV files so the csv module can handle line endings correctly.

#7 Assuming every JSON object contains the required keys.

Why it happens: External or incomplete JSON data may omit keys, so use validation, membership checks, or get() before relying on required fields.

Incorrect Approach
script.py
python
Assuming every JSON object contains the required keys.
Correct Solution
script.py
python
Validate required fields, use get() for optional fields, and handle missing data deliberately.

Key takeaway: Validate required fields, use get() for optional fields, and handle missing data deliberately.

#8 Catching every exception and ignoring it.

Why it happens: Ignoring every exception hides malformed input and operational failures; catch expected errors and provide a useful response or diagnostic.

Incorrect Approach
script.py
python
Catching every exception and ignoring it.
Correct Solution
script.py
python
Handle specific expected errors and report failures clearly.

Key takeaway: Handle specific expected errors and report failures clearly.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is the difference between JSON and CSV?
Answer:
JSON represents structured values such as objects, arrays, strings, numbers, booleans, and null. CSV represents tabular records and fields. JSON is useful for nested data and API messages, while CSV is useful for datasets arranged in rows and columns.
Q2:What is the difference between json.load() and json.loads()?
Answer:
json.load(file) reads and parses JSON from a file-like object. json.loads(text) parses JSON from a string.
Q3:What is the difference between json.dump() and json.dumps()?
Answer:
json.dump(data, file) serializes a Python object and writes it to a file-like object. json.dumps(data) returns the serialized JSON text as a string.
Q4:Why use the with statement when reading or writing data files?
Answer:
The with statement manages the file resource and closes it when the block finishes, including when an exception occurs.
Q5:Why do CSV readers usually return strings?
Answer:
CSV stores fields as text and does not inherently declare application-level types. The application must convert and validate fields when it needs integers, floats, dates, or other types.
Q6:What is the difference between csv.reader() and csv.DictReader()?
Answer:
reader() returns rows as lists. DictReader() maps row values to dictionary keys, using the header row as field names by default.
Q7:What is the purpose of newline='' in CSV file operations?
Answer:
It lets the csv module handle newline conventions correctly and avoids issues with embedded newlines in quoted fields or extra carriage returns on some platforms.
Q8:How do you handle invalid JSON?
Answer:
Catch json.JSONDecodeError around json.load() or json.loads(), report the parsing failure, and decide whether to reject, repair, or request a valid input. Do not silently accept malformed data.
Q9:How would you write a CSV file with column names?
Answer:
Create a csv.DictWriter with a fieldnames sequence, open the file using newline='' and the intended encoding, call writeheader(), and write records with writerow() or writerows().
Q10:When should you choose JSON over CSV?
Answer:
Choose JSON when the data contains nested objects, arrays, or different value types, or when communicating structured data with an API. Choose CSV when the data is naturally a table with consistent columns and needs to be exchanged with spreadsheet or tabular-data tools.

Key takeaways

  • Use JSON for structured data and CSV for tabular records.
  • loads() parses JSON text, load() reads JSON from a file, dumps() creates JSON text, and dump() writes JSON to a file.
  • Use the json and csv standard-library modules instead of manually parsing formatted data.
  • CSV reader values are normally strings; convert and validate them explicitly.
  • Use DictReader and DictWriter when column names make records easier to understand.
  • Open text files with the intended encoding and use newline='' for CSV files.
  • Handle parsing errors, missing files, missing keys, and invalid field values deliberately.
  • Valid syntax does not guarantee valid application data; validate the fields your program relies on.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: