Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Golang Equal JSON Strings

JSON string equality

A little utility for testing if 2 json strings are equal, for use in tests.

Example

go run main.go '{"dog": 5, "cat": 3}' '{"cat":3, "dog": 5}'

Caveats

  • You may want to use a matcher library (like gomega) that has a function for this, since some of the other functionality in those libraries is pretty awesome
package main
import (
"encoding/json"
"flag"
"fmt"
"os"
"reflect"
)
func AreEqualJSON(s1, s2 string) (bool, error) {
var o1 interface{}
var o2 interface{}
var err error
err = json.Unmarshal([]byte(s1), &o1)
if err != nil {
return false, fmt.Errorf("Error mashalling string 1 :: %s", err.Error())
}
err = json.Unmarshal([]byte(s2), &o2)
if err != nil {
return false, fmt.Errorf("Error mashalling string 2 :: %s", err.Error())
}
return reflect.DeepEqual(o1, o2), nil
}
func main() {
flag.Parse()
if len(flag.Args()) < 2 {
fmt.Println("Need 2 arguments that are both json strings")
os.Exit(1)
}
s1 := flag.Args()[0]
s2 := flag.Args()[1]
fmt.Println("s1:: ", s1)
fmt.Println("s2:: ", s2)
areEqual, err := AreEqualJSON(s1, s2)
if err != nil {
fmt.Println("Error mashalling strings", err.Error())
}
fmt.Println("Equal:: ", areEqual)
}
Owner

turtlemonvh commented Apr 18, 2016

So the omega library uses this same approach:
https://github.com/onsi/gomega/blob/v1.0/matchers.go#L164
https://github.com/onsi/gomega/blob/v1.0/matchers/match_json_matcher.go#L15

The only difference is they marshall into an interface{} instead of a map[string]interface{} so they can handle arrays too.

I'm changing mine to use the same approach.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment