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
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
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
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
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
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
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
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
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
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
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
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 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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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?
Q2:What is the difference between json.load() and json.loads()?
Q3:What is the difference between json.dump() and json.dumps()?
Q4:Why use the with statement when reading or writing data files?
Q5:Why do CSV readers usually return strings?
Q6:What is the difference between csv.reader() and csv.DictReader()?
Q7:What is the purpose of newline='' in CSV file operations?
Q8:How do you handle invalid JSON?
Q9:How would you write a CSV file with column names?
Q10:When should you choose JSON over CSV?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: