keras-team/keras · error · TypeError

Targets not JSON Serializable: {targets}

Error message

Targets not JSON Serializable: {targets}

What it means

The targets counterpart of the data check: TimeseriesGenerator.get_config json.dumps the targets (after tolist() for numpy arrays), and any non-JSON-serializable target value (datetimes, Decimals, custom classes) triggers this TypeError.

Source

Thrown at keras/src/legacy/preprocessing/sequence.py:150

        Returns:
            A Python dictionary with the TimeseriesGenerator configuration.
        """
        data = self.data
        if type(self.data).__module__ == np.__name__:
            data = self.data.tolist()
        try:
            json_data = json.dumps(data)
        except TypeError as e:
            raise TypeError(f"Data not JSON Serializable: {data}") from e

        targets = self.targets
        if type(self.targets).__module__ == np.__name__:
            targets = self.targets.tolist()
        try:
            json_targets = json.dumps(targets)
        except TypeError as e:
            raise TypeError(f"Targets not JSON Serializable: {targets}") from e

        config = super().get_config()
        config.update(
            {
                "data": json_data,
                "targets": json_targets,
                "length": self.length,
                "sampling_rate": self.sampling_rate,
                "stride": self.stride,
                "start_index": self.start_index,
                "end_index": self.end_index,
                "shuffle": self.shuffle,
                "reverse": self.reverse,
                "batch_size": self.batch_size,
            }
        )
        return config

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Make targets numeric (float/int) before building the generator
  2. Keep a separate mapping for original values and pass integer codes as targets
  3. Prefer tf.keras.utils.timeseries_dataset_from_array in new code

Example fix

# before
gen = TimeseriesGenerator(prices, dates, length=5)
# after
gen = TimeseriesGenerator(prices, dates.astype('int64'), length=5)
Defensive patterns

Strategy: validation

Validate before calling

try:
    json.dumps(np.asarray(targets).tolist())
except TypeError:
    targets = np.asarray(targets).astype('float64')

Try / catch

try:
    gen.get_config()
except TypeError as e:
    if 'Targets not JSON Serializable' not in str(e):
        raise

Prevention

When it happens

Trigger: get_config() on a generator whose targets contain datetime or Decimal values or are stored as object-dtype arrays.

Common situations: Forecasting pipelines whose labels are timestamps or currency Decimals; save paths that capture generator configs.

Related errors


AI-assisted analysis of keras-team/keras@7a34a03db6 (2026-08-25). Data as JSON: /api/errors/4499fa6d625221b8. Report an issue: GitHub.