json.MarshalIndent and json.Encoder.SetIndent doesn't indent output from json.Marshaller implementers, which means that e.g. k8s.io/apimachinery/pkg/apis/meta/v1/unstructured objects are never marshalled with the right indentation. This could be fixed upstream in encoding/json or github.com/json-iterator/go by walking (using an JSON iterator) the []byte return value of MarshalJSON(), and indenting accordingly whenever the right tokens are found.
As far as I understand, the implementations mentioned already validate the output of MarshalJSON(), i.e. verify that the syntax is correct, and as such already do "most" of the work needed.
The workaround for this would be to first do a normal Marshal of the object, and then do a json.Indent into a temporary buffer, only to later return the buf.Bytes() in case of MarshalIndent or write the buffer contents to the underlying io.Writer. It would of course be nice if json.Indent supported writing directly to any io.Writer, so the buffer "middle-man" could be avoided.
json.MarshalIndent
andjson.Encoder.SetIndent
doesn't indent output fromjson.Marshaller
implementers, which means that e.g.k8s.io/apimachinery/pkg/apis/meta/v1/unstructured
objects are never marshalled with the right indentation. This could be fixed upstream inencoding/json
orgithub.com/json-iterator/go
by walking (using an JSON iterator) the[]byte
return value ofMarshalJSON()
, and indenting accordingly whenever the right tokens are found.As far as I understand, the implementations mentioned already validate the output of
MarshalJSON()
, i.e. verify that the syntax is correct, and as such already do "most" of the work needed.The workaround for this would be to first do a normal
Marshal
of the object, and then do ajson.Indent
into a temporary buffer, only to later return thebuf.Bytes()
in case ofMarshalIndent
or write the buffer contents to the underlyingio.Writer
. It would of course be nice ifjson.Indent
supported writing directly to anyio.Writer
, so the buffer "middle-man" could be avoided.