[{"data":1,"prerenderedAt":66},["ShallowReactive",2],{"qa-\u002Fpython\u002Fstdlib\u002Fserialization":3},{"page":4,"siblings":53,"blog":44},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":20,"path":21,"questions":22,"related":44,"seo":45,"seoDescription":46,"stem":47,"subtopic":48,"topic":49,"topicSlug":50,"updated":51,"__hash__":52},"qa\u002Fpython\u002Fstdlib\u002Fserialization.md","Serialization",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,4,"\u002Fpython\u002Fstdlib\u002Fserialization",[23,28,32,36,40],{"id":24,"difficulty":25,"q":26,"a":27},"json-dumps-loads","easy","How do json.dumps and json.loads work, and how do Python types map to JSON?","**`json.dumps`** serializes a Python object **to** a JSON string; **`json.loads`**\nparses a JSON string **back** into Python objects. The `dump`\u002F`load` variants\n(no `s`) work with file objects instead. The conversion follows a fixed type\nmapping.\n\n```python\nimport json\n\ndata = {\"name\": \"Ada\", \"age\": 36, \"tags\": [\"math\"], \"active\": True}\ns = json.dumps(data)            # dict -> JSON string\nback = json.loads(s)            # JSON string -> dict\n\nwith open(\"out.json\", \"w\") as f:\n    json.dump(data, f)          # write to file\n```\n\nThe mapping: `dict`->object, `list`\u002F`tuple`->array, `str`->string, `int`\u002F`float`\n->number, `True`\u002F`False`->`true`\u002F`false`, `None`->`null`. Note **tuples become\narrays** (you get a list back), and **dict keys are coerced to strings**. JSON has\nno native date, set, or bytes type.\n",{"id":29,"difficulty":14,"q":30,"a":31},"json-custom-encoding","How do you serialize an object JSON doesn't support by default?","Unsupported types raise `TypeError: ... is not JSON serializable`. The two standard\nfixes are the **`default=` callback** (a function called for any unserializable\nobject, returning a JSON-friendly substitute) or a custom **`JSONEncoder` subclass**\npassed via **`cls=`**.\n\n```python\nimport json\nfrom datetime import datetime\n\ndef encode(obj):\n    if isinstance(obj, datetime):\n        return obj.isoformat()        # turn it into a string\n    raise TypeError(f\"not serializable: {type(obj)}\")\n\njson.dumps({\"when\": datetime.now()}, default=encode)\n\nclass MyEncoder(json.JSONEncoder):    # the class-based alternative\n    def default(self, obj):\n        if isinstance(obj, set):\n            return list(obj)\n        return super().default(obj)\njson.dumps({1, 2, 3}, cls=MyEncoder)\n```\n\nUse `default=` for a quick one-off; subclass `JSONEncoder` when you want reusable\nencoding logic. On the way back, use `object_hook` in `loads` to reconstruct custom\ntypes.\n",{"id":33,"difficulty":14,"q":34,"a":35},"csv-reader-dictreader","What is the difference between csv.reader and csv.DictReader?","Both read CSV files, but the row format differs. **`csv.reader`** yields each row as\na **list of strings** indexed by position. **`csv.DictReader`** treats the first row\nas **headers** and yields each row as a **dict** keyed by column name — far more\nreadable and robust to column reordering.\n\n```python\nimport csv\n\nwith open(\"people.csv\", newline=\"\") as f:\n    for row in csv.reader(f):\n        print(row[0], row[1])         # positional — brittle\n\nwith open(\"people.csv\", newline=\"\") as f:\n    for row in csv.DictReader(f):\n        print(row[\"name\"], row[\"age\"])  # by header — clear\n```\n\nAlways open CSV files with **`newline=\"\"`** to let the `csv` module handle line\nendings correctly. Prefer `DictReader`\u002F`DictWriter` for named-column access; use the\nplain `reader` for headerless or purely positional data.\n",{"id":37,"difficulty":14,"q":38,"a":39},"pickle-vs-json","What is the difference between pickle and json, and what is the security warning?","**`json`** is a **text**, language-independent format for **simple data** (dicts,\nlists, numbers, strings). **`pickle`** is a **binary**, Python-specific format that\ncan serialize **almost any Python object** (custom classes, functions references,\nnested objects). The crucial caveat: **never unpickle untrusted data**.\n\n```python\nimport json, pickle\n\njson.dumps({\"x\": 1})              # \"{\\\"x\\\": 1}\" — readable, portable\npickle.dumps({\"x\": 1})            # b'\\x80\\x04...' — binary, Python-only\n\n# DANGER: unpickling runs arbitrary code embedded in the data\npickle.loads(untrusted_bytes)     # can execute malicious payloads!\n```\n\n`pickle.loads` can **execute arbitrary code** during deserialization, so it's a\nremote-code-execution risk on attacker-controlled input. Rule of thumb: use **json**\nfor config, APIs, and anything crossing a trust boundary; use **pickle** only for\ntrusted, internal Python-to-Python data (e.g. caches you wrote yourself).\n",{"id":41,"difficulty":14,"q":42,"a":43},"serializing-datetimes","How do you serialize datetimes to JSON and back?","JSON has **no date type**, so a `datetime` must be converted to a **string** — the\nISO 8601 format via **`.isoformat()`** is the standard choice because it's\nunambiguous and parseable. On the way out use `default=`; on the way back parse the\nstring with `datetime.fromisoformat()`.\n\n```python\nimport json\nfrom datetime import datetime\n\nevent = {\"name\": \"launch\", \"at\": datetime(2026, 6, 18, 14, 30)}\n\ntext = json.dumps(event, default=lambda o: o.isoformat())\n# '{\"name\": \"launch\", \"at\": \"2026-06-18T14:30:00\"}'\n\nraw = json.loads(text)\nraw[\"at\"] = datetime.fromisoformat(raw[\"at\"])   # back to datetime\n```\n\nJSON can't tell a date-string from an ordinary string, so you must know which fields\nto re-parse (or use `object_hook`). Prefer ISO strings in **UTC** for portability,\nand convert to local time only at display.\n",null,{"description":11},"Python interview questions on json.dumps\u002Floads and type mapping, custom JSON encoding, csv reader vs DictReader, pickle vs json and pickle security, and serializing datetimes.","python\u002Fstdlib\u002Fserialization","JSON, CSV & pickle","Standard Library Essentials","stdlib","2026-06-18","viTtNO-ARfmO9ag13muRGsYBkN9JO5C_NMhcGlPbP1U",[54,58,61,65],{"subtopic":55,"path":56,"order":57},"Regular Expressions","\u002Fpython\u002Fstdlib\u002Fregex",1,{"subtopic":59,"path":60,"order":12},"Files, pathlib & os","\u002Fpython\u002Fstdlib\u002Ffiles-pathlib",{"subtopic":62,"path":63,"order":64},"datetime","\u002Fpython\u002Fstdlib\u002Fdatetime",3,{"subtopic":48,"path":21,"order":20},1781808681949]