How to minify JSON in go?

Hi,

I am learning go and trying to work out how to minify small JSON fragments. So far I have…

// return a minified JSON input string
// return an error encountered during minifiying or reading minified bytes
func minify(jsonB []byte) ([]byte, error) {

	var buff *bytes.Buffer = new(bytes.Buffer)
	errCompact := json.Compact(buff, jsonB)
	if errCompact != nil {
		newErr := fmt.Errorf("failure encountered compacting json := %v", errCompact)
		return []byte{}, newErr
	}

	b, err := ioutil.ReadAll(buff)
	if err != nil {
		readErr := fmt.Errorf("read buffer error encountered := %v", err)
		return []byte{}, readErr
	}

	return b, nil
}

Included a test stub at go playground here

Am I on the right track with this or is there an easier way?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.