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.


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


  • 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 (
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() {
if len(flag.Args()) < 2 {
fmt.Println("Need 2 arguments that are both json strings")
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 commented Apr 18, 2016

So the omega library uses this same approach:

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