How to produce JSON with sorted keys in Go?

The json package always orders keys when marshalling. Specifically:

  • Maps have their keys sorted lexicographically

  • Structs keys are marshalled in the order defined in the struct

The implementation lives here ATM:

  • http://golang.org/src/pkg/encoding/json/encode.go?#L359

Gustavo Niemeyer gave great answer, just a small handy snippet I use to validate and reorder/normalize []byte representation of json when required

func JSONRemarshal(bytes []byte) ([]byte, error) {
    var ifce interface{}
    err := json.Unmarshal(bytes, &ifce)
    if err != nil {
        return nil, err
    }
    return json.Marshal(ifce)
}

Tags:

Json

Go