我有一张 map
{
"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
}
最佳答案
要回答原始问题,请使用有序 map
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 无法保证 map 的顺序得到尊重,因此最好使用数组代替 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)
当重新加载数组时,它将以正确的顺序排列
关于sorting - 如何防止 map 排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469714/