File Handling
JSON Files
Comprehensive JSON handling in Python — serialization, deserialization, custom encoders/decoders, working with JSON Lines, and streaming large JSON data.
Interview: JSON is the universal data interchange format — interviewers test your ability to parse, generate, and manipulate JSON data efficiently.
JSON (JavaScript Object Notation) is the most common data format for APIs, configuration files, and data storage. Python's json module provides four core functions for working with JSON data, plus support for custom serialization of complex objects.
Core JSON Functions
json.dump(obj, file)— serialize Python object to JSON filejson.dumps(obj)— serialize Python object to JSON stringjson.load(file)— deserialize JSON file to Python objectjson.loads(string)— deserialize JSON string to Python object- Key parameters:
indent(pretty-print),sort_keys,ensure_ascii,default(custom encoder)
Type Mapping
- JSON object → Python dict, JSON array → Python list
- JSON string → Python str, JSON number → int or float
- JSON true/false → Python True/False, JSON null → None
- Not supported: sets, tuples, datetime, custom classes — need custom encoder
Custom Encoders and Decoders
For complex objects, you can subclass json.JSONEncoder or use the default parameter:
defaultfunction: receives objects that can't be serialized, returns serializable versionobject_hookfunction: called for every decoded JSON object — useful for custom deserialization- JSON Lines (
.jsonl): one JSON object per line — ideal for streaming large datasets
Interview Insight
Know how to handle non-serializable types (datetime, custom classes) with custom encoders. Be prepared to explain the difference between json.load/loads and json.dump/dumps, and when to use JSON Lines for large datasets.
Use Cases
REST API communication — sending and receiving JSON data
Configuration files — app settings in human-readable format
Data storage — JSON Lines for large-scale log files and datasets
Inter-process communication — serializing data between services
Web scraping — parsing JSON responses from web APIs
Common Mistakes
Forgetting json.dump writes to file, json.dumps returns string — different functions
Not handling non-serializable types — datetime, set, and custom classes need encoders
Loading untrusted JSON without validation — can cause unexpected data types
Reading entire large JSON file into memory — use JSON Lines for streaming instead
Not using indent parameter during debugging — makes JSON unreadable in output