Last active
July 4, 2022 10:48
-
-
Save geraldstanje/71747cca7457c3d6452430abfbb237ee to your computer and use it in GitHub Desktop.
use gocmp for json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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