JSON, CSV & pickle Interview Questions & Answers

5 questions Updated 2026-06-18

Python interview questions on json.dumps/loads and type mapping, custom JSON encoding, csv reader vs DictReader, pickle vs json and pickle security, and serializing datetimes.

json.dumps serializes a Python object to a JSON string; json.loads parses a JSON string back into Python objects. The dump/load variants (no s) work with file objects instead. The conversion follows a fixed type mapping.

import json

data = {"name": "Ada", "age": 36, "tags": ["math"], "active": True}
s = json.dumps(data)            # dict -> JSON string
back = json.loads(s)            # JSON string -> dict

with open("out.json", "w") as f:
    json.dump(data, f)          # write to file

The mapping: dict->object, list/tuple->array, str->string, int/float ->number, True/False->true/false, None->null. Note tuples become arrays (you get a list back), and dict keys are coerced to strings. JSON has no native date, set, or bytes type.

Unsupported types raise TypeError: ... is not JSON serializable. The two standard fixes are the default= callback (a function called for any unserializable object, returning a JSON-friendly substitute) or a custom JSONEncoder subclass passed via cls=.

import json
from datetime import datetime

def encode(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()        # turn it into a string
    raise TypeError(f"not serializable: {type(obj)}")

json.dumps({"when": datetime.now()}, default=encode)

class MyEncoder(json.JSONEncoder):    # the class-based alternative
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return super().default(obj)
json.dumps({1, 2, 3}, cls=MyEncoder)

Use default= for a quick one-off; subclass JSONEncoder when you want reusable encoding logic. On the way back, use object_hook in loads to reconstruct custom types.

Both read CSV files, but the row format differs. csv.reader yields each row as a list of strings indexed by position. csv.DictReader treats the first row as headers and yields each row as a dict keyed by column name — far more readable and robust to column reordering.

import csv

with open("people.csv", newline="") as f:
    for row in csv.reader(f):
        print(row[0], row[1])         # positional — brittle

with open("people.csv", newline="") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["age"])  # by header — clear

Always open CSV files with newline="" to let the csv module handle line endings correctly. Prefer DictReader/DictWriter for named-column access; use the plain reader for headerless or purely positional data.

json is a text, language-independent format for simple data (dicts, lists, numbers, strings). pickle is a binary, Python-specific format that can serialize almost any Python object (custom classes, functions references, nested objects). The crucial caveat: never unpickle untrusted data.

import json, pickle

json.dumps({"x": 1})              # "{\"x\": 1}" — readable, portable
pickle.dumps({"x": 1})            # b'\x80\x04...' — binary, Python-only

# DANGER: unpickling runs arbitrary code embedded in the data
pickle.loads(untrusted_bytes)     # can execute malicious payloads!

pickle.loads can execute arbitrary code during deserialization, so it's a remote-code-execution risk on attacker-controlled input. Rule of thumb: use json for config, APIs, and anything crossing a trust boundary; use pickle only for trusted, internal Python-to-Python data (e.g. caches you wrote yourself).

JSON has no date type, so a datetime must be converted to a string — the ISO 8601 format via .isoformat() is the standard choice because it's unambiguous and parseable. On the way out use default=; on the way back parse the string with datetime.fromisoformat().

import json
from datetime import datetime

event = {"name": "launch", "at": datetime(2026, 6, 18, 14, 30)}

text = json.dumps(event, default=lambda o: o.isoformat())
# '{"name": "launch", "at": "2026-06-18T14:30:00"}'

raw = json.loads(text)
raw["at"] = datetime.fromisoformat(raw["at"])   # back to datetime

JSON can't tell a date-string from an ordinary string, so you must know which fields to re-parse (or use object_hook). Prefer ISO strings in UTC for portability, and convert to local time only at display.

Practice tests are coming soon

Get notified when interactive mock interviews and quizzes launch.