-
Notifications
You must be signed in to change notification settings - Fork 1
/
camel_snake.go
60 lines (49 loc) · 1.23 KB
/
camel_snake.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package normalizejson
import (
"bytes"
"strings"
"unicode"
"github.com/Grivn/normalizejson/regex"
)
func JSONSchemaCamel2Snake(data []byte) []byte {
return regex.CamelCaseJSONKey.ReplaceAllFunc(data, convertBytesCamel2Snake)
}
func JSONSchemaSnake2Camel(data []byte) []byte {
return regex.JSONKey.ReplaceAllFunc(data, convertBytesSnake2Camel)
}
func convertBytesCamel2Snake(match []byte) []byte {
return bytes.ToLower(regex.CamelCase.ReplaceAll(match, []byte(`${1}_${2}`)))
}
func convertBytesSnake2Camel(match []byte) []byte {
key := readKey(match)
res := toCamelCase(key)
return createKey(res)
}
func toCamelCase(source string) string {
strList := strings.Split(source, "_")
for index, str := range strList {
strList[index] = firstToUpper(str)
}
res := strings.Join(strList, "")
return firstToLower(res)
}
func firstToUpper(str string) string {
for i, v := range str {
return string(unicode.ToUpper(v)) + str[i+1:]
}
return ""
}
func firstToLower(str string) string {
for i, v := range str {
return string(unicode.ToLower(v)) + str[i+1:]
}
return ""
}
func readKey(raw []byte) string {
str := string(raw)
key := str[1 : len(str)-2]
return key
}
func createKey(key string) []byte {
return []byte(`"` + key + `":`)
}