How to produce JSON with sorted keys in Go?

前端 未结 2 631
鱼传尺愫
鱼传尺愫 2020-12-17 09:37

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=(\'         


        
相关标签:
2条回答
  • 2020-12-17 10:06

    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
    0 讨论(0)
  • 2020-12-17 10:13

    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 []byte{}, err
        }
        output, err := json.Marshal(ifce)
        if err != nil {
            return []byte{}, err
        }
        return output, nil
    }
    
    0 讨论(0)
提交回复
热议问题