Skip to content

Instantly share code, notes, and snippets.

@geraldstanje geraldstanje/main.go

Last active Oct 7, 2019
Embed
What would you like to do?
use gocmp for json
package main
import (
"encoding/json"
"fmt"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
// s1 and s2 are equal if you sort the slice called SelectedData and ignore the key called "foo"
func main() {
s1 := []byte(`{
"SelectedData":[
{
"ID":5,
"bla":"hello5",
"foo":123
},
{
"ID":1,
"bla":"hello1",
"foo":123
},
{
"ID":2,
"bla":"hello2",
"foo":123
}
]
}`)
s2 := []byte(`{
"SelectedData":[
{
"ID":1,
"bla":"hello1",
"foo":123
},
{
"ID":5,
"bla":"hello5",
"foo":123
},
{
"ID":2,
"bla":"hello2",
"foo":222
}
]
}`)
fmt.Println("cmp.Equal:", cmp.Equal(s1, s2, transformJSON, sortIDs))
}
var transformJSON = cmpopts.AcyclicTransformer("ParseJSON", func(in []byte) (out interface{}) {
if err := json.Unmarshal(in, &out); err != nil {
return in
}
if entities, ok := out.(map[string]interface{}); ok {
if selectedData, ok2 := entities["SelectedData"].([]interface{}); ok2 {
for _,v := range selectedData {
if m, ok3 := v.(map[string]interface{}); ok3 {
delete(m, "foo")
}
}
}
}
return out
})
var sortIDs = cmpopts.SortSlices(func(x, y interface{}) bool {
obj1, _ := x.(map[string]interface{})
obj2, _ := y.(map[string]interface{})
id1, _ := obj1["ID"].(float64)
id2, _ := obj2["ID"].(float64)
return id1 < id2
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.