sorting - 如何防止地图排序?
问题描述
我有一张地图
{
"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
}
解决方案
要回答原始问题,请使用有序地图
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)
重新加载数组时,它将以正确的顺序排列
推荐阅读
- json - 将对象反序列化为包含委托属性的数据类(带委托的继承)
- python - 在 print() 上返回空查询集
- docker - 在字符串值的情况下,Docker-compose 合并 2 个配置会产生错误的类型
- javascript - 无法访问 JS 对象值
- node.js - “serviceworker”必须是您的网络应用清单中的字典
- javascript - 上下文提供程序不会在状态更改时重新呈现
- javascript - 如何在保留图层的同时将 SVG 转换为 PNG?
- java - 为什么在使用 selenium webdriver 读取正文中提到的站点上显示的距离时没有返回任何内容
- python - 在 Python3 中循环来自 JSON 字典的两个值
- javascript - 使用 node.js 下载 csv 文件