我有一个使用字符串作为键和值的映射。我有一个key数组,用于指定map的顺序。

我想将该映射序列化为JSON,但要保持数组上定义的顺序。

我想将其序列化为:

1
2
3
4
{
 "name":"John",
 "age":"20"
}

但是,如果我直接序列化map,则密钥按key顺序排列:

1
2
3
4
{
 "age":"20",
 "name":"John"
}

使用有序 map

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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输出可能更好

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// 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 排序?