Skip to content

Instantly share code, notes, and snippets.

@turtlemonvh
Last active November 9, 2022 17:51
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turtlemonvh/e4f7404e28387fadb8ad275a99596f67 to your computer and use it in GitHub Desktop.
Save turtlemonvh/e4f7404e28387fadb8ad275a99596f67 to your computer and use it in GitHub Desktop.
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)
}
@turtlemonvh
Copy link
Author

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.

@dolmen
Copy link

dolmen commented Jul 15, 2018

null, true, "abc" are also valid JSON. That's why interface{} should be used instead of map[string]interface{}.

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