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?