Skip to content

Commit

Permalink
Simplify DataType()
Browse files Browse the repository at this point in the history
  • Loading branch information
asido committed Aug 26, 2019
1 parent 6fc8c9e commit 18c1612
Showing 1 changed file with 13 additions and 19 deletions.
32 changes: 13 additions & 19 deletions keywords.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,37 +19,31 @@ var primitiveTypes = map[string]bool{
"integer": true,
}

var dataTypes = map[reflect.Kind]string{
reflect.Bool: "boolean",
reflect.Float64: "number",
reflect.String: "string",
reflect.Array: "array",
reflect.Slice: "array",
reflect.Map: "object",
reflect.Struct: "object",
}

// 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 {
if data == nil {
return "null"
}

kind := reflect.TypeOf(data).Kind()
typeStr, ok := dataTypes[kind]
if !ok {
return "unknown"
}

if kind == reflect.Float64 {
switch reflect.TypeOf(data).Kind() {
case reflect.Bool:
return "boolean"
case reflect.Float64:
number := reflect.ValueOf(data).Float()
if float64(int(number)) == number {
return "integer"
}
return "number"
case reflect.String:
return "string"
case reflect.Array, reflect.Slice:
return "array"
case reflect.Map, reflect.Struct:
return "object"
default:
return "unknown"
}

return typeStr
}

// Type specifies one of the six json primitive types.
Expand Down

0 comments on commit 18c1612

Please sign in to comment.