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.

Revisions

  1. 117 revised this gist Mar 19, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion main.go
    Original 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
    // @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
  2. 117 created this gist Mar 19, 2020.
    53 changes: 53 additions & 0 deletions main.go
    Original 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
    }