Created
September 29, 2013 16:35
-
-
Save jcinnamond/6754087 to your computer and use it in GitHub Desktop.
Go json and types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"errors" | |
"fmt" | |
"reflect" | |
) | |
func compAny(a, b interface{}) bool { | |
if reflect.TypeOf(a) != reflect.TypeOf(b) { | |
return false | |
} | |
switch a.(type) { | |
case map[string]interface{}: | |
x := a.(map[string]interface{}) | |
y := b.(map[string]interface{}) | |
eq := true | |
for k, v := range x { | |
eq = eq && compAny(v, y[k]) | |
} | |
return eq | |
case []interface{}: | |
x := a.([]interface{}) | |
y := b.([]interface{}) | |
if len(x) != len(y) { | |
return false | |
} | |
eq := true | |
for i, v := range x { | |
eq = eq && compAny(v, y[i]) | |
} | |
return eq | |
case bool, float64, string, nil: | |
return a == b | |
default: | |
fmt.Printf("Don't know how to compare %# and %#\n", a, b) | |
return false | |
} | |
} | |
func jsonEqual(a, b string) (bool, error) { | |
var json1, json2 interface{} | |
if err := json.Unmarshal([]byte(a), &json1); err != nil { | |
return false, errors.New(fmt.Sprintf("`%v` is not valid json", a)) | |
} | |
if err := json.Unmarshal([]byte(b), &json2); err != nil { | |
return false, errors.New(fmt.Sprintf("`%v` is not valid json", b)) | |
} | |
return compAny(json1, json2), nil | |
} | |
func main() { | |
raw1 := `{"values": [null, "john", 1, true]}` | |
raw2 := `{"values": [null, "john", 1, true]}` | |
eq, err := jsonEqual(raw1, raw2) | |
if err != nil { | |
fmt.Println("Can't compare json:", err) | |
} else if eq { | |
fmt.Println("JSON strings are equal") | |
} else { | |
fmt.Println("JSON strings are different") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment