Skip to content

Instantly share code, notes, and snippets.

@jamesmoey
Last active November 28, 2016 01:18
Show Gist options
  • Save jamesmoey/28a0ab6e39cb9b668c503695f3df0540 to your computer and use it in GitHub Desktop.
Save jamesmoey/28a0ab6e39cb9b668c503695f3df0540 to your computer and use it in GitHub Desktop.
Go - Convert unsafe map interface into JSON safe
import (
"strconv"
"reflect"
)
func makeMapJsonSafe(unsafe interface{}) (interface{}) {
if unsafe != nil && reflect.TypeOf(unsafe).Kind() == reflect.Map {
if isArray(unsafe.(map[interface{}]interface{})) {
var jsonSafe = make([]interface{}, len(unsafe.(map[interface{}]interface{})))
for key, value := range unsafe.(map[interface{}]interface{}) {
if reflect.TypeOf(key).Kind() == reflect.String {
index, e := strconv.Atoi(key.(string))
if e == nil {
jsonSafe[index] = makeMapJsonSafe(value)
}
} else if reflect.TypeOf(key).Kind() == reflect.Int64 {
jsonSafe[key.(int64)] = makeMapJsonSafe(value)
}
}
return jsonSafe
} else {
var jsonSafe = make(map[string]interface{})
for key, value := range unsafe.(map[interface{}]interface{}) {
jsonSafe[key.(string)] = makeMapJsonSafe(value)
}
return jsonSafe
}
} else {
return unsafe
}
}
/*
* Check if the map is actually an array?
*/
func isArray(subject map[interface{}]interface{}) bool {
for key := range subject {
if reflect.TypeOf(key).Kind() == reflect.String {
_, e = strconv.Atoi(key.(string))
if e != nil {
return false
}
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment