Python / Core Python Fundamentals Interview Questions
How do you parse and build JSON payloads in Python?
Python's built-in json module converts between JSON strings/files and Python objects. The mapping is: JSON object ↔ Python dict, JSON array ↔ Python list, JSON string ↔ Python str, JSON number ↔ Python int/float, JSON true/false ↔ Python True/False, JSON null ↔ Python None.
import json # --- Parsing (deserialising) --- # From a JSON string (e.g., API response body) json_str = '{"name": "Alice", "age": 30, "tags": ["admin", "user"]}' data = json.loads(json_str) # loads = load string print(data['name']) # Alice print(data['tags'][0]) # admin # From a file with open('config.json', encoding='utf-8') as f: config = json.load(f) # load (no s) = load file # --- Building (serialising) --- payload = {'user_id': 42, 'scores': [95, 87, 100], 'active': True} # To a string json_out = json.dumps(payload, indent=2) # pretty-printed print(json_out) # To a file with open('output.json', 'w', encoding='utf-8') as f: json.dump(payload, f, indent=2) # Handling dates â not natively serialisable from datetime import date json.dumps({'date': date.today().isoformat()}) # convert to string first
Common pitfalls: JSON keys are always strings, but Python dicts can have non-string keys — serialising a dict with int keys will convert them to strings, which can break round-trip assumptions. Python's datetime, Decimal, and custom objects are not JSON-serialisable by default — you must either convert them before serialising or provide a custom default= encoder function to json.dumps().
More Related questions...