json

json.dumps(obj) turns Python data into a JSON string. json.loads(text) turns a string back into Python data. (dump and load, without the s, work with files.)

The types map like this: dict to object, list and tuple to array, str to string, int and float to number, True to true, and None to null.

The round trip is not always exact:

  • A tuple comes back as a list.
  • Dict keys must be strings in JSON, so the key 1 comes back as "1".
  • Sets, dates and your own classes raise TypeError. Convert them first, for example sorted(my_set) or d.isoformat().

indent=2 makes the output readable, and sort_keys=True makes it the same every time, which helps when you compare JSON in tests.

JSON is the default answer for API payloads in System design interviews.

Run it, then try json.loads("{'a': 1}"). JSON needs double quotes.