keras-team/keras · error · TypeError
Unable to serialize to JSON. Unrecognized type .
Error message
Unable to serialize {obj} to JSON. Unrecognized type {type(obj)}. What it means
get_json_type is the fallback serializer behind model.to_json(); after handling dicts, lists, tuples, numpy scalars, enums, and bytes, any unrecognized object type raises this TypeError naming the object and its type. It is the catch-all for 'this config value cannot be written as JSON'.
Solutions
- Locate the object named in the message and convert it to a primitive in the custom layer's get_config
- Ensure custom get_config returns only str/int/float/bool/list/dict values
- Use model.save('model.keras'), which supports richer Python objects
Example fix
# before
class MyLayer(layers.Layer):
def get_config(self):
return {'fn': self._fn} # callable -> TypeError
# after
def get_config(self):
return {'fn_name': self._fn.__name__} Defensive patterns
Strategy: validation
Validate before calling
import json cfg = layer.get_config() json.dumps(cfg) # dry-run: raises before saving if non-serializable
Type guard
def config_json_safe(cfg):
try:
json.dumps(cfg)
return True
except TypeError:
return False Try / catch
try:
model.to_json()
except TypeError as e:
if 'Unrecognized type' not in str(e):
raise
model.save('model.keras') Prevention
- Unit-test custom get_config with a json.dumps round-trip
When it happens
Trigger: model.to_json() when a layer's config holds a non-JSON value: a custom class instance, a function reference, or a type the serializer never learned.
Common situations: Custom layers whose get_config returns arbitrary Python objects; passing callables or non-primitive constants as layer arguments.
Understand the failure class
Background: "JSON serialization failed", "not JSON serializable", "Failed to serialize": why JSON marshaling errors happen and how to fix them — this error's family across 46 libraries.
Related errors
- Data not JSON Serializable
- Layer ' ' was never built and thus it doesn't have any…
- Targets not JSON Serializable
- Unable to serialize to JSON, because the TypeSpec class has…
- A Sequential model configuration must be a dictionary…
AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25).
Data as JSON: /api/errors/653fe5dd9cd19fc8.
Report an issue: GitHub.
Appendix: source
Thrown at keras/src/legacy/saving/json_utils.py:218
)
if tf.available and isinstance(obj, tf.__internal__.CompositeTensor):
spec = tf.type_spec_from_value(obj)
tensors = []
for tensor in tf.nest.flatten(obj, expand_composites=True):
tensors.append((tensor.dtype.name, tensor.numpy().tolist()))
return {
"class_name": "CompositeTensor",
"spec": get_json_type(spec),
"tensors": tensors,
}
if isinstance(obj, enum.Enum):
return obj.value
if isinstance(obj, bytes):
return {"class_name": "__bytes__", "value": obj.decode("utf-8")}
raise TypeError(
f"Unable to serialize {obj} to JSON. Unrecognized type {type(obj)}."
)
View on GitHub (pinned to 7a34a03db6)