{"record":{"id":"7475f887b33f0089","repo":"django/django","slug":"error-deserializing-object-exc","errorCode":null,"errorMessage":"Error deserializing object: {exc}","messagePattern":"Error deserializing object: (.+?)","errorType":"exception","errorClass":"DeserializationError","httpStatus":null,"severity":"error","filePath":"django/core/serializers/json.py","lineNumber":81,"sourceCode":"\n    def __init__(self, stream_or_string, **options):\n        if not isinstance(stream_or_string, (bytes, str)):\n            stream_or_string = stream_or_string.read()\n        if isinstance(stream_or_string, bytes):\n            stream_or_string = stream_or_string.decode()\n        try:\n            objects = json.loads(stream_or_string)\n        except Exception as exc:\n            raise DeserializationError() from exc\n        super().__init__(objects, **options)\n\n    def _handle_object(self, obj):\n        try:\n            yield from super()._handle_object(obj)\n        except (GeneratorExit, DeserializationError):\n            raise\n        except Exception as exc:\n            raise DeserializationError(f\"Error deserializing object: {exc}\") from exc\n\n\nclass DjangoJSONEncoder(json.JSONEncoder):\n    \"\"\"\n    JSONEncoder subclass that knows how to encode date/time, decimal types, and\n    UUIDs.\n    \"\"\"\n\n    def default(self, o):\n        # See \"Date Time String Format\" in the ECMA-262 specification.\n        if isinstance(o, datetime.datetime):\n            r = o.isoformat(\n                sep=\"T\",\n                timespec=\"milliseconds\" if o.microsecond // 1000 else \"seconds\",\n            )\n            if r.endswith(\"+00:00\"):\n                r = r.removesuffix(\"+00:00\") + \"Z\"\n            return r","sourceCodeStart":63,"sourceCodeEnd":99,"githubUrl":"https://github.com/django/django/blob/b5388a3a80cafcce2e34196d8e81cf5b48eb33bb/django/core/serializers/json.py#L63-L99","documentation":"`Deserializer._handle_object` in the JSON serializer (json.py:75-81) wraps any non-`GeneratorExit`/non-`DeserializationError` exception raised while turning one deserialized dict into a model instance. It re-raises as `DeserializationError(f\"Error deserializing object: {exc}\")`, chaining the original via `from exc`. This is the catch-all for per-object failures during JSON fixture loading.","triggerScenarios":"Loading JSON fixture data where an individual object dict references an unknown model, a field value fails `to_python()` conversion, a FK/M2M lookup misses, or `build_instance` raises. The wrapping happens after `json.loads` succeeded, so the JSON itself was syntactically valid.","commonSituations":"Fixture exported from an older Django with fields since removed from the model; a CharField value that fails validation/conversion (e.g. bad date string); a ContentType or natural-key target missing in the target DB; model moved/renamed between apps.","solutions":["Read the chained `__cause__` exception to find the real failure (field name, model, value).","Load with `ignorenonexistent=True` to skip fields/objects that no longer match the model.","Re-export the fixture from a schema matching the target model definitions.","If a FK target is missing, load the referenced fixture first or use `handle_forward_references=True`."],"exampleFix":"// before\nfor obj in serializers.deserialize('json', payload):\n    obj.save()  # DeserializationError: Error deserializing object: ...\n// after\ntry:\n    for obj in serializers.deserialize('json', payload, ignorenonexistent=True):\n        obj.save()\nexcept DeserializationError as exc:\n    raise RuntimeError('fixture row failed: %r', exc.__cause__) from exc","handlingStrategy":"try-catch","validationCode":"import json\nfrom django.core import serializers\nfrom django.core.serializers.base import DeserializationError\n\ndef safe_load_json(payload):\n    try:\n        objects = json.loads(payload)\n    except ValueError as e:\n        raise ValueError(f'invalid JSON document: {e}')\n    if not isinstance(objects, list):\n        raise ValueError('expected a JSON list of objects')\n    return objects","typeGuard":null,"tryCatchPattern":"from django.core.serializers.base import DeserializationError\ntry:\n    for obj in serializers.deserialize('json', payload, ignorenonexistent=True):\n        obj.save()\nexcept DeserializationError as exc:\n    # exc.__cause__ holds the real failure; exc.args[0] is the wrapped message\n    raise RuntimeError(f'JSON object failed: {exc}') from exc.__cause__","preventionTips":["Load fixtures with ignorenonexistent=True to tolerate schema drift.","Inspect exc.__cause__ for the precise field/value at fault.","Re-export fixtures from a schema matching the target models."],"tags":["serializers","json","deserialization","fixtures"],"backgroundTag":null,"analyzedSha":"b5388a3a80cafcce2e34196d8e81cf5b48eb33bb","analyzedAt":"2026-08-10T17:37:52.993Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}