kubernetes/kops · error

unable to marshal JSON: %v

Error message

unable to marshal JSON: %v

What it means

In JSON output mode, `kops get sshpublickeys` marshals the SSHKeyItem slice with encoding/json. JSON Marshal fails on unsupported types (func, chan, cycles); when that happens the command returns "unable to marshal JSON: %v". Like the YAML variant, this is not reachable through user input alone with the current struct.

Source

Thrown at cmd/kops/get_sshpublickeys.go:131

		}
		t := &tables.Table{}
		t.AddColumn("ID", func(i *SSHKeyItem) string {
			return i.ID
		})
		return t.Render(items, out, "ID")

	case OutputYaml:
		y, err := yaml.Marshal(items)
		if err != nil {
			return fmt.Errorf("unable to marshal YAML: %v", err)
		}
		if _, err := out.Write(y); err != nil {
			return fmt.Errorf("error writing to output: %v", err)
		}
	case OutputJSON:
		j, err := json.Marshal(items)
		if err != nil {
			return fmt.Errorf("unable to marshal JSON: %v", err)
		}
		if _, err := out.Write(j); err != nil {
			return fmt.Errorf("error writing to output: %v", err)
		}
	default:
		return fmt.Errorf("unknown output format: %q", options.Output)
	}

	return nil
}

View on GitHub (pinned to 4c8573c808)

Solutions

  1. Read the wrapped error: json: unsupported type: <T> names the exact field type
  2. Change the offending field to a serializable type or add json:"-" to omit it
  3. Verify with `-o yaml` to see if the issue is JSON-specific (e.g. a bad MarshalJSON implementation)

Example fix

// before
type SSHKeyItem struct {
	Hook func() // unsupported by encoding/json
}
// after
type SSHKeyItem struct {
	Hook func() `json:"-"` // excluded from marshaling
}
Defensive patterns

Strategy: type-guard

Type guard

func jsonSerializable(v interface{}) error {
	_, err := json.Marshal(v)
	return err
}
// call before rendering: if err := jsonSerializable(items); err != nil { ... }

Try / catch

if err := runGetSSHPublicKeys(opts); err != nil {
	if strings.HasPrefix(err.Error(), "unable to marshal JSON:") {
		log.Printf("items not JSON-serializable: %v", err)
		return errUnsupportedFormat
	}
	return err
}

Prevention

When it happens

Trigger: Only via code changes adding unserializable fields to SSHKeyItem (or embedding types with MarshalJSON errors) in a patched/forked build.

Common situations: Custom kOps forks; local patches adding e.g. a func or a self-referencing pointer to the item struct.

Related errors


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