首页 > 解决方案 > 如何防止地图排序?

问题描述

我有一张地图

{
"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
}

标签: sortingdictionarygo

解决方案


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

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)

重新加载数组时,它将以正确的顺序排列


推荐阅读