luxas / deklarative

A library to work with serialized declarative configuration, e.g. Kubernetes-style YAML in a file
Apache License 2.0
0 stars 0 forks source link

Support `json.MarshalIndent` & `json.Encoder.SetIndent` for `json.Marshaller` implementations #1

Open luxas opened 3 years ago

luxas commented 3 years ago

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.