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 firstCommon 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().
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
