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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料