Reputation: 1037
package main
import (
"encoding/json"
"fmt"
"reflect"
)
func main() {
nodeArray := map[string]interface{}{
"meta": map[string]interface{}{
"category": "paragraph"}, "content": []string{"111"}}
// content is number as 111 or array
b, _ := json.Marshal(&nodeArray)
var nodeArrayTest map[string]interface{}
json.Unmarshal(b, &nodeArrayTest)
if !reflect.DeepEqual(nodeArray, nodeArrayTest) {
fmt.Println("!!!! odeArray and nodeArrayTest should be equal")
} else {
fmt.Println("odeArray and nodeArrayTest equal")
}
}
Why when the interface map has array(content is number as 111 or array), the return of DeepEqual is false? And when the content value is a string, a map, the DeepEqual is true.
Upvotes: 1
Views: 3824
Reputation: 1
aaa := map[string]interface {}{"meta":map[string]interface {}{"category":"paragraph"}, "content":[]string{"111","222"}}
bbb := map[string]interface {}{"content":[]string{"222","111"}, "meta":map[string]interface {}{"category":"paragraph"}}
It's not true.
Upvotes: -2
Reputation: 43899
Printing out the two values, in question, we can see that they are different:
nodeArray = map[string]interface {}{"meta":map[string]interface {}{"category":"paragraph"}, "content":[]string{"111"}}
nodeArrayTest = map[string]interface {}{"content":[]interface {}{"111"}, "meta":map[string]interface {}{"category":"paragraph"}}
In particular, nodeArray["content"]
is a []string
slice, while nodeArrayTest["content"]
is a a []interface{}
slice. The reflect.DeepEqual
function does not consider these equal due to the type mismatch.
The encoding/json
module decodes into an []interface{}
slice because JSON arrays can contain values of different types.
Upvotes: 3