如何防止地图排序?

时间:2018-09-23 19:52:20

标签: sorting dictionary go

我有一张地图

{
"m_key": 123,
"z_key": 123,
"a_key": 123,
"f_key": 123
}

当我尝试从中制作一个json并进行打印时,我的json将按键排序,并且我得到json:

{
"a_key": 123,
"f_key": 123,
"m_key": 123,
"z_key": 123
}

1 个答案:

答案 0 :(得分:-1)

要回答原始问题,请使用有序地图

package main

import (
    "encoding/json"
    "fmt"
    "github.com/iancoleman/orderedmap"
)

func main() {

    o := orderedmap.New()

    // use Set instead of o["a"] = 1

    o.Set("m_key", "123") // go json.Marshall doesn't like integers
    o.Set("z_key", "123")
    o.Set("a_key", "123")
    o.Set("f_key", "123")

    // serialize to a json string using encoding/json
    prettyBytes, _ := json.Marshal(o)
    fmt.Printf("%s", prettyBytes)
}

但是根据规范https://json-schema.org/latest/json-schema-core.html#rfc.section.4.2 无法保证兑现了地图的顺序,因此最好使用数组代替json输出

   // convert to array
    fmt.Printf("\n\n\n")
    arr := make([]string, 8)
    c := 0
    for _, k := range o.Keys() {
            arr[c] = k
            c++
            v, _ := o.Get(k)
            arr[c], _ = v.(string)
            c++
    }

    morePretty, _ := json.Marshal(arr)
    fmt.Printf("%s", morePretty)

重新加载数组时,其顺序正确