Skip to the solution
EasyBackend12 min read

How do you convert between Python objects and JSON?

397 views

The problem

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.loads work with strings; json.dump / json.load work with file objects
  • The type mapping: object to dict, array to list, string to str, number to int or float, true/false to True/False, null to None
  • The round trip is lossy: tuples come back as lists, non-string dict keys become strings, and set, datetime, Decimal or custom classes raise TypeError unless you pass default=
  • Decoding custom types with object_hook (or parse_float=Decimal for exact numbers); for real APIs, a validation layer such as dataclasses or Pydantic
  • Useful options: indent, sort_keys, separators, ensure_ascii=False; errors arrive as json.JSONDecodeError, a ValueError
  • Gotchas: NaN/Infinity are emitted by default (not valid JSON; use allow_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.

  • json
  • serialization

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read · 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythondumps and loads: the type mapping, lossy round trips, formatting and errors
PythonCustom types with default= and object_hook, plus the NaN, Decimal and duplicate-key gotchas

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 27 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

How does comparison chaining (a < b < c) work?

Continue