Sorting JSON Keys in Go
The Python json package provides a sort_keys option to produce JSON with keys in a sorted order. This article explores how to achieve similar functionality in Go's encoding/json package.
Solution
In Go, the json package automatically sorts the keys of:
Implementation Details
The implementation of key sorting can be found in the encode.go file within the encoding/json package:
func (enc *encodeState) encodeMap(v reflect.Value) { m := v.Interface().(map[string]interface{}) if enc.indent { enc.write(`{` + enc.indentPrefix) } else { enc.write(`{`) } enc.mapStarted = true keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } sort.Strings(keys) for i, k := range keys { enc.encodeValue(reflect.ValueOf(k)) enc.write(`:`) enc.encodeValue(reflect.ValueOf(m[k])) if i < len(m)-1 { enc.write(`,`) } } enc.write(`}`) enc.mapStarted = false }
This implementation ensures that map keys are sorted lexicographically, and struct keys are sorted based on their order within the struct definition.
The above is the detailed content of How Can I Sort JSON Keys When Encoding JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!