Skip to content

Commit

Permalink
feat(type): identify custom struct as objects
Browse files Browse the repository at this point in the history
Merge pull request #54 from asido/master
  • Loading branch information
b5 authored Aug 26, 2019
2 parents 9f11b79 + c1722b7 commit 585074c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
19 changes: 11 additions & 8 deletions keywords.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,24 @@ var primitiveTypes = map[string]bool{
// DataType gives the primitive json type of a standard json-decoded value, plus the special case
// "integer" for when numbers are whole
func DataType(data interface{}) string {
switch v := data.(type) {
case nil:
if data == nil {
return "null"
case bool:
}

switch reflect.TypeOf(data).Kind() {
case reflect.Bool:
return "boolean"
case float64:
if float64(int(v)) == v {
case reflect.Float64:
number := reflect.ValueOf(data).Float()
if float64(int(number)) == number {
return "integer"
}
return "number"
case string:
case reflect.String:
return "string"
case []interface{}:
case reflect.Array, reflect.Slice:
return "array"
case map[string]interface{}:
case reflect.Map, reflect.Struct:
return "object"
default:
return "unknown"
Expand Down
11 changes: 9 additions & 2 deletions schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -449,17 +449,24 @@ func runJSONTests(t *testing.T, testFilepaths []string) {
}

func TestDataType(t *testing.T) {
type customObject struct {}
type customNumber float64

cases := []struct {
data interface{}
expect string
}{
{nil, "null"},
{struct{}{}, "unknown"},
{float64(4), "integer"},
{float64(4.5), "number"},
{customNumber(4.5), "number"},
{"foo", "string"},
{map[string]interface{}{}, "object"},
{[]interface{}{}, "array"},
{[0]interface{}{}, "array"},
{map[string]interface{}{}, "object"},
{struct{}{}, "object"},
{customObject{}, "object"},
{int8(42), "unknown"},
}

for i, c := range cases {
Expand Down

0 comments on commit 585074c

Please sign in to comment.