Deep equality testing with json marshaling in golang

Given these two tests:

func TestEqualWhat(t *testing.T) { testMarshalUnmarshal(t, map[string]interface{}{"a":"b"}) testMarshalUnmarshal(t, map[string]interface{}{"a":5}) } 

Where the testMarshalUnmarshal helper just marshals json and returns:

 func testMarshalUnmarshal(t *testing.T, in map[string]interface{}) { //marshal the object to a string jsb, err := json.Marshal(in); if err != nil { log.Printf("Unable to marshal msg") t.FailNow() } //unmarshal to a map res := make(map[string]interface{}) if err := json.Unmarshal(jsb, &res); err != nil { t.FailNow() } if !reflect.DeepEqual(in, res) { log.Printf("\nExpected %#v\nbut got %#v", in, res) t.FailNow() } } 

Why does the first test case fail and the second fail? The test result is as follows:

 Expected map[string]interface {}{"a":5} but got map[string]interface {}{"a":5} --- FAIL: TestEqualWhat (0.00 seconds) 

Here is a similar code on the go playground so you can easily crack it.

+7
source share
1 answer

I get it! JSON has only one numeric type, which is a floating point, so all integers are converted in Float64 to a marshal / non-marshal process. So, on the map res 5 is float64 instead of int.

Here is a playground that provides context and evidence of what I'm talking about.

+13
source

All Articles