Question presented to candidate: "You get JSON from an API and need to send JSON back. How do you convert between JSON and Python objects, and what happens with types JSON does not have, like dates, sets or your own classes?"
What a strong answer should cover:
json.dumps/json.loadswork with strings;json.dump/json.loadwork with file objects- The type mapping: object to
dict, array tolist, string tostr, number tointorfloat,true/falsetoTrue/False,nulltoNone - The round trip is lossy: tuples come back as lists, non-string dict keys become strings, and
set,datetime,Decimalor custom classes raiseTypeErrorunless you passdefault= - Decoding custom types with
object_hook(orparse_float=Decimalfor exact numbers); for real APIs, a validation layer such as dataclasses or Pydantic - Useful options:
indent,sort_keys,separators,ensure_ascii=False; errors arrive asjson.JSONDecodeError, aValueError - Gotchas:
NaN/Infinityare emitted by default (not valid JSON; useallow_nan=False), and duplicate keys silently keep the last value
Clarifying questions expected:
- Do the objects contain non-JSON types such as dates, decimals or sets?
- Does the output need to be stable (sorted keys) or human-readable (indented)?
Code / implementation expected: Yes — dumps/loads plus a default= function for one custom type.