Skip to content

Instantly share code, notes, and snippets.

@117
Created March 19, 2020 03:39
Show Gist options
  • Save 117/0d1d79cd3b33f72da9530ceb966966a3 to your computer and use it in GitHub Desktop.
Save 117/0d1d79cd3b33f72da9530ceb966966a3 to your computer and use it in GitHub Desktop.
Check if JSON matches a struct in Go.
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment