keras-team/keras · error · TypeError

Data not JSON Serializable: {data}

Error message

Data not JSON Serializable: {data}

What it means

TimeseriesGenerator.get_config serializes its data array to JSON for config round-tripping. It converts numpy arrays via tolist(), but any other non-JSON-serializable payload (datetimes, pd.Timestamp, Decimal, custom objects) makes json.dumps raise TypeError, re-raised with this message.

Source

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

        targets = np.array([self.targets[row] for row in rows])

        if self.reverse:
            return samples[:, ::-1, ...], targets
        return samples, targets

    def get_config(self):
        """Returns the TimeseriesGenerator configuration as Python dictionary.

        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,

View on GitHub (pinned to 7a34a03db6)

Solutions

  1. Convert datetimes to numeric features before constructing the generator (e.g. epoch seconds via .astype('int64') for datetime64)
  2. Cast object-dtype arrays to float/int yourself
  3. For new code use tf.keras.utils.timeseries_dataset_from_array, which does not embed data in configs

Example fix

# before
gen = TimeseriesGenerator(times, values, length=5)  # times: datetime64
# after
nums = (times - np.datetime64('1970-01-01')).astype('int64')
gen = TimeseriesGenerator(nums, values, length=5)
Defensive patterns

Strategy: validation

Validate before calling

try:
    json.dumps(np.asarray(data).tolist())
except TypeError:
    data = np.asarray(data).astype('float64')  # or datetime->int conversion

Type guard

def json_safe(a):
    return all(isinstance(v, (int, float, str, bool, list, dict, type(None)))
               for v in np.asarray(a).ravel().tolist()[:100])

Try / catch

try:
    gen.get_config()
except TypeError as e:
    if 'not JSON Serializable' not in str(e):
        raise
    # convert datetimes to ints and retry

Prevention

When it happens

Trigger: Calling .get_config() (directly or via model-saving utilities that capture configs) on a generator whose data holds datetime objects or an object-dtype numpy array.

Common situations: Feeding time-indexed financial/weather data with datetime64 or object-dtype arrays into the legacy generator, then saving the model; migrating old Keras 2.x code forward.

Related errors


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