duanbinian2243 2016-04-18 15:16
浏览 99
已采纳

从Map和Struct封送的JSON中的排序差异

When marshaling from a map[string]interface{} and an equivalent struct, the JSON returned are similar but different in the internal order of the keys likewise:

var arg1 = map[string]interface{}{
    "foo": "bar",
    "baz": map[string]interface{}{
        "bee": "boo",
    },
}

type Arg struct {
    Foo string                 `json:"foo"`
    Baz map[string]interface{} `json:"baz"`
}

var arg2 = &Arg{
    Foo: "bar",
    Baz: map[string]interface{}{
        "bee": "boo",
    },
}

func main() {
    result1, _ := json.Marshal(arg1)
    result2, _ := json.Marshal(arg2)

    fmt.Println(reflect.DeepEqual(result1, result2)
    fmt.Println(string(result1))
    fmt.Println(string(result2))

    // false
    // {"baz":{"bee":"boo"},"foo":"bar"}
    // {"foo":"bar","baz":{"bee":"boo"}}

}

Check the playground here.

Although in JSON the order doesn't matter, I'd like to know why are the results ordered differently?

  • 写回答

2条回答 默认 最新

  • dskvfdxgdo2422392 2016-04-18 17:04
    关注

    The encoding/json package marshals maps in sorted key order and structs in the order that the fields are declared.

    Although the order used by the encoding/json package is not documented, it's safe to assume that maps are marshaled in sorted key order and structs are marshaled in field declaration order. There are many tests in the standard library and elsewhere that depend on these orders.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog