Created
March 19, 2020 03:39
-
-
Save 117/0d1d79cd3b33f72da9530ceb966966a3 to your computer and use it in GitHub Desktop.
Revisions
-
117 revised this gist
Mar 19, 2020 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -39,7 +39,7 @@ func CompareJSONToStruct(bytes []byte, empty interface{}) bool { // 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 -
117 created this gist
Mar 19, 2020 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,53 @@ 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 }