Skip to content

Instantly share code, notes, and snippets.

@joshbeard
Last active December 6, 2022 03:25
Show Gist options
  • Save joshbeard/11500ef154b0bdda81d83888aef04eba to your computer and use it in GitHub Desktop.
Save joshbeard/11500ef154b0bdda81d83888aef04eba to your computer and use it in GitHub Desktop.
Go: JSON match
// Demonstrate checking if two JSON strings match.
// Formatted JSON can be compared with minified JSON and will match as long as
// the keys and values are the same.
package main
import (
"encoding/json"
"fmt"
"log"
"reflect"
)
func jsonMatch(one, two string) (bool, error) {
var v1, v2 interface{}
err := json.Unmarshal([]byte(one), &v1)
if err != nil {
return false, fmt.Errorf("Error unmarshalling first item:", err)
}
err = json.Unmarshal([]byte(two), &v2)
if err != nil {
fmt.Println("Error unmarshal two:", err)
return false, fmt.Errorf("Error unmarshalling second item:", err)
}
if reflect.DeepEqual(v1, v2) {
return true, nil
}
return false, nil
}
func main() {
one := `{"myKey": true, "yourKey": "yours"}`
two := `{"myKey": true, "yourKey": "yours"}`
match, err := jsonMatch(one, two)
if err != nil {
log.Fatal("Failed to compare JSON:", err)
}
if match {
fmt.Println("Match")
} else {
fmt.Println("Don't match")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment