mirror of
https://github.com/rancher/norman.git
synced 2025-08-31 06:35:09 +00:00
Add util methods to convert to idiomatic json/yaml key formats
This commit is contained in:
@@ -211,3 +211,40 @@ func EncodeToMap(obj interface{}) (map[string]interface{}, error) {
|
||||
dec.UseNumber()
|
||||
return result, dec.Decode(&result)
|
||||
}
|
||||
|
||||
func ToJSONKey(str string) string {
|
||||
parts := strings.Split(str, "_")
|
||||
for i := 1; i < len(parts); i++ {
|
||||
parts[i] = strings.Title(parts[i])
|
||||
}
|
||||
|
||||
return strings.Join(parts, "")
|
||||
}
|
||||
|
||||
func ToYAMLKey(str string) string {
|
||||
var result []rune
|
||||
cap := false
|
||||
|
||||
for i, r := range []rune(str) {
|
||||
if i == 0 {
|
||||
if unicode.IsUpper(r) {
|
||||
cap = true
|
||||
}
|
||||
result = append(result, unicode.ToLower(r))
|
||||
continue
|
||||
}
|
||||
|
||||
if unicode.IsUpper(r) {
|
||||
if cap {
|
||||
result = append(result, unicode.ToLower(r))
|
||||
} else {
|
||||
result = append(result, '_', unicode.ToLower(r))
|
||||
}
|
||||
} else {
|
||||
cap = false
|
||||
result = append(result, r)
|
||||
}
|
||||
}
|
||||
|
||||
return string(result)
|
||||
}
|
||||
|
Reference in New Issue
Block a user