{"record":{"id":"d69686dda339bade","repo":"pallets/flask","slug":"object-of-type-type-o-name-is-not-json-seri","errorCode":null,"errorMessage":"Object of type {type(o).__name__} is not JSON serializable","messagePattern":"Object of type (.+?) is not JSON serializable","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/flask/json/provider.py","lineNumber":121,"sourceCode":"        \"\"\"\n        obj = self._prepare_response_obj(args, kwargs)\n        return self._app.response_class(self.dumps(obj), mimetype=\"application/json\")\n\n\ndef _default(o: t.Any) -> t.Any:\n    if isinstance(o, date):\n        return http_date(o)\n\n    if isinstance(o, (decimal.Decimal, uuid.UUID)):\n        return str(o)\n\n    if dataclasses and dataclasses.is_dataclass(o):\n        return dataclasses.asdict(o)  # type: ignore[arg-type]\n\n    if hasattr(o, \"__html__\"):\n        return str(o.__html__())\n\n    raise TypeError(f\"Object of type {type(o).__name__} is not JSON serializable\")\n\n\nclass DefaultJSONProvider(JSONProvider):\n    \"\"\"Provide JSON operations using Python's built-in :mod:`json`\n    library. Serializes the following additional data types:\n\n    -   :class:`datetime.datetime` and :class:`datetime.date` are\n        serialized to :rfc:`822` strings. This is the same as the HTTP\n        date format.\n    -   :class:`uuid.UUID` is serialized to a string.\n    -   :class:`dataclasses.dataclass` is passed to\n        :func:`dataclasses.asdict`.\n    -   :class:`~markupsafe.Markup` (or any object with a ``__html__``\n        method) will call the ``__html__`` method to get a string.\n    \"\"\"\n\n    default: t.Callable[[t.Any], t.Any] = staticmethod(_default)\n    \"\"\"Apply this function to any object that :meth:`json.dumps` does","sourceCodeStart":103,"sourceCodeEnd":139,"githubUrl":"https://github.com/pallets/flask/blob/3596b1ab61cea85edb8970e83ff61daa073facf8/src/flask/json/provider.py#L103-L139","documentation":"_default(o) is Flask's JSON encoder fallback for objects the standard json module cannot serialize. It handles date/datetime, Decimal, UUID, dataclasses, and objects with __html__. If an object matches none of these, it raises TypeError naming the object's type. This surfaces during jsonify/dumps when your data contains an unsupported type like a SQLAlchemy model instance, a set, bytes, or a custom class.","triggerScenarios":"Returning jsonify(obj) where obj (or a nested value) is a type Flask does not serialize by default: a set, bytes, a custom class without __html__, a SQLAlchemy InstrumentedList, an Enum, or a Pandas DataFrame. _default is called by json.dumps for each unhandled object.","commonSituations":"Passing ORM objects to jsonify instead of dicts. Forgetting to convert a set to a list. Returning bytes or a custom value object. Using Enum members in API responses without a default encoder.","solutions":["Convert the object to a serializable form before jsonify: model.to_dict(), list(my_set), my_bytes.decode(), enum.value.","Subclass DefaultJSONProvider and override _default or dumps to handle your custom types, then set app.json.","Use marshmallow/pydantic to serialize complex objects to dicts."],"exampleFix":"# before\n@app.route('/u')\ndef user():\n    return jsonify(db.session.get(User, 1))  # User not serializable\n\n# after\n@app.route('/u')\ndef user():\n    u = db.session.get(User, 1)\n    return jsonify({'id': u.id, 'name': u.name})","handlingStrategy":"type-guard","validationCode":"import dataclasses, datetime, decimal, uuid, json\n\ndef is_json_serializable(o) -> bool:\n    return isinstance(o, (str, int, float, bool, type(None), list, tuple, dict,\n                          datetime.date, datetime.datetime, decimal.Decimal, uuid.UUID)) \\\n        or (dataclasses.is_dataclass(o)) or hasattr(o, '__html__')\n\n# validate before jsonify\ndef assert_serializable(obj):\n    json.dumps(obj, default=lambda o: (_ for _ in ()).throw(\n        TypeError(f'{type(o).__name__} not serializable')) if not is_json_serializable(o) else o))","typeGuard":"import datetime, decimal, uuid, dataclasses\n\ndef is_default_serializable(o) -> bool:\n    return isinstance(o, (str, int, float, bool, type(None), list, tuple, dict,\n                          datetime.date, decimal.Decimal, uuid.UUID)) \\\n        or dataclasses.is_dataclass(o) or hasattr(o, '__html__')","tryCatchPattern":"from flask.json.provider import DefaultJSONProvider\nimport json\n\nclass SafeJSONProvider(DefaultJSONProvider):\n    def dumps(self, obj, **kw):\n        try:\n            return super().dumps(obj, **kw)\n        except TypeError:\n            return super().dumps(str(obj), **kw)\napp.json = SafeJSONProvider(app)","preventionTips":["Convert ORM/model objects to dicts before jsonify.","Register a custom JSONProvider.default for app-wide custom types.","Unit-test response payloads with json.dumps to catch unserializable types early."],"tags":["flask","json","serialization"],"backgroundTag":null,"analyzedSha":"3596b1ab61cea85edb8970e83ff61daa073facf8","analyzedAt":"2026-08-11T20:11:52.622Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}