Reputation: 3745
I'm trying to run some tests on json objects. Currently I have a function to compare the json string and output an error message if they don't match:
func assertJsonEqual(expected, actual string) bool {
actualStruct := make(map[string]interface{})
expectedStruct := make(map[string]interface{})
json.Unmarshal([]byte(expected), &expectedStruct)
json.Unmarshal([]byte(actual), &actualStruct)
if !reflect.DeepEqual(expectedStruct, actualStruct) {
log.Errorf("Expected: %#v\n but got %#v", expectedStruct, actualStruct)
return false
}
return true
}
The problem is this makes it really hard to see exactly which key is missing or extra in the actual tool. I'm thinking about building a simple diff of the map keys, but am wondering if there is an existing library that already does this?
Upvotes: 1
Views: 1932
Reputation: 48086
There's not an existing function, it's like 5 lines of code.
diff := &[]string{} // initialize some storage for the diff
for _, k := range map1 { // range over one of the maps
if _, ok := map2[k]; !ok { // check if the key from the first map exists in the second
diff = append(diff, k)
}
}
Upvotes: 2