Skip to content

Commit

Permalink
feat(type): identify custom struct as objects
Browse files Browse the repository at this point in the history
Limiting type `object` to `map[string]interface{}` and nothing else is restrictive.
Since the library allows to pass data structures as input, some of it can contain
user defined data structures and we shall be able to identify them as `object`
instead of `unknown`.
  • Loading branch information
asido committed Aug 26, 2019
1 parent 9f11b79 commit c1722b7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
19 changes: 11 additions & 8 deletions keywords.go
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
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 c1722b7

Please sign in to comment.