Select Git revision
map_utils.go
map_utils.go 1.57 KiB
package map_utils
import (
"fmt"
"strconv"
"strings"
)
// MapStringInterfaceToMapStringString converts a generic value typed map to a map with string values
func MapStringInterfaceToMapStringString(inputMap map[string]interface{}) map[string]string {
query := make(map[string]string)
for mapKey, mapVal := range inputMap {
// Check if mapVal is a slice or a single value
switch mapValTyped := mapVal.(type) {
case []interface{}:
// Slice - convert each element individually
var mapValString []string
// Loop through each element in the slice and check the type
for _, sliceElem := range mapValTyped {
switch sliceElemTyped := sliceElem.(type) {
case string:
// Enclose strings in escaped quotations
mapValString = append(mapValString, fmt.Sprintf("\"%v\"", sliceElemTyped))
case float64:
// Use FormatFloat for least amount of precision.
mapValString = append(mapValString, strconv.FormatFloat(sliceElemTyped, 'f', -1, 64))
default:
// Convert to string
mapValString = append(mapValString, fmt.Sprintf("%v", sliceElemTyped))
}
}
// Join as a comma seperated array
query[mapKey] = "[" + strings.Join(mapValString, ",") + "]"
default:
// Single value - convert to string
query[mapKey] = fmt.Sprintf("%v", mapVal)
}
}
return query
}
// MergeMaps If there are similar properties in the maps, the last one will be used as the value
func MergeMaps(maps ...map[string]string) map[string]string {
ret := map[string]string{}
for _, mapV := range maps {
for k, v := range mapV {
ret[k] = v
}
}
return ret
}