package main import ( "encoding/json" "fmt" "reflect" "strings" ) // Example - An example JSON-friendly struct. type Example struct { A string `json:"A"` B int64 `json:"B"` C string `json:"C"` D struct { E string `json:"E"` } `json:"D"` } func main() { fmt.Println(CompareJSONToStruct([]byte(`{"A": "null","B": 0,"C": "null","D": {"E": "null"}}`), Example{})) } // CompareJSONToStruct - Compare the fields in the JSON []byte slice to a struct. // Only top level fields are checked, nested struct fields are ignored. func CompareJSONToStruct(bytes []byte, empty interface{}) bool { var mapped map[string]interface{} if err := json.Unmarshal(bytes, &mapped); err != nil { return false } emptyValue := reflect.ValueOf(empty).Type() // check if number of fields is the same if len(mapped) != emptyValue.NumField() { return false } // check if field names are the same for key := range mapped { // @todo go deeper into nested struct fields if field, found := emptyValue.FieldByName(key); found { if !strings.EqualFold(key, strings.Split(field.Tag.Get("json"), ",")[0]) { return false } } } // @todo check for field type mismatching return true }