sheki
sheki

Reputation: 9370

How to produce JSON with sorted keys in Go?

In python you can produce JSON with keys in sorted order by doing

import json
print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4, separators=(',', ': '))

I have not found a similar option in Go. Any ideas how I can achieve similar behavior in go?

Upvotes: 47

Views: 40362

Answers (2)

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)
}

Upvotes: 13

Gustavo Niemeyer
Gustavo Niemeyer

Reputation: 23011

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:

Upvotes: 98

Related Questions