Q1. How do you work with JSON in Python?
Use the json module. json.dumps() converts Python object to JSON string, json.dump() writes to file. json.loads() parses JSON string to Python object, json.load() reads from file. Example:
import json
data = {"name": "Alice", "age": 30}
json_str = json.dumps(data)
with open(''data.json'', ''w'') as f:
json.dump(data, f)Q2. What is the difference between json.load() and json.loads()?
json.load() reads a JSON file and returns a Python object. json.loads() parses a JSON string and returns a Python object. Similarly, json.dump() writes Python object to file, json.dumps() returns a JSON string.
Q3. How do you pretty-print JSON?
Use the indent parameter in json.dumps() or json.dump(). Example:
json.dumps(data, indent=4)Q4. How do you handle non-serializable objects?
You can define a custom encoder by subclassing json.JSONEncoder and overriding default() method. Alternatively, convert objects to serializable format (e.g., dictionary) before serialization. Example:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)Q5. What are the common JSON serialization errors?
TypeError occurs when trying to serialize non-serializable types like datetime or custom objects. Use default parameter to handle them. Also, ensure the data is JSON-serializable: only dict, list, str, int, float, bool, None types.
