kubernetes/kops · error

error converting to json: %w

Error message

error converting to json: %w

What it means

SortSlice sorts a []any by each element's JSON representation. If json.Marshal fails for any element — e.g. a channel, func, complex number, or a cyclic reference — the sort aborts with this wrapped error. It is a wrapper around encoding/json's 'json: unsupported type' error.

Source

Thrown at pkg/jsonutils/transform.go:133

		s[i] = v2
	}

	return s, nil
}

// SortSlice sorts a slice of any values, ordered by their JSON representations.
// This is not very efficient, but is convenient for small slice where we don't know their types.
func SortSlice(s []any) ([]any, error) {
	type entry struct {
		o       any
		sortKey string
	}

	var entries []entry
	for i := range s {
		j, err := json.Marshal(s[i])
		if err != nil {
			return nil, fmt.Errorf("error converting to json: %w", err)
		}
		entries = append(entries, entry{o: s[i], sortKey: string(j)})
	}

	sort.Slice(entries, func(i, j int) bool {
		return entries[i].sortKey < entries[j].sortKey
	})

	out := make([]any, 0, len(s))
	for i := range s {
		out = append(out, entries[i].o)
	}

	return out, nil
}

// visitPrimitive is a helper function that visits a primitive value in the JSON tree
func (o *Transformer) visitPrimitive(v any, _ string) (any, error) {

View on GitHub (pinned to 4c8573c808)

Solutions

  1. Remove or replace unmarshalable elements (chan/func/complex) before sorting.
  2. Marshal-test each element with json.Marshal beforehand to find the offending one.
  3. Use a custom sort key (e.g. fmt.Sprintf("%v", v) or a dedicated field) instead of full JSON marshalling.

Example fix

// before
sorted, err := jsonutils.SortSlice(items) // items contains a func
// after
for i, v := range items {
	if _, err := json.Marshal(v); err != nil {
		return fmt.Errorf("item %d unmarshalable: %w", i, err)
	}
}
sorted, err := jsonutils.SortSlice(items)
Defensive patterns

Strategy: validation

Validate before calling

for i, v := range s {
	if _, err := json.Marshal(v); err != nil {
		return fmt.Errorf("element %d is not JSON-marshalable: %w", i, err)
	}
}

Try / catch

sorted, err := jsonutils.SortSlice(s)
if err != nil {
	return fmt.Errorf("cannot sort slice: %w", err)
}

Prevention

When it happens

Trigger: Calling jsonutils.SortSlice on a slice containing unmarshalable values (chan, func, complex128), a struct with only unmarshalable fields, or a data structure containing a reference cycle.

Common situations: Sorting mixed/unknown data where an element accidentally holds a callback or channel; sorting trees built by hand rather than decoded from JSON.

Related errors


AI-assisted analysis of kubernetes/kops@4c8573c808 (2026-09-05). Data as JSON: /api/errors/ba6111dd9306f5df. Report an issue: GitHub.