-
Notifications
You must be signed in to change notification settings - Fork 3
/
phpjson.go
50 lines (45 loc) · 994 Bytes
/
phpjson.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
package phpjson
import (
"fmt"
"github.com/dtapps/go-library/utils/gojson"
"reflect"
"strings"
)
func Encode(v interface{}) (string, error) {
bytes, err := gojson.Marshal(v)
if err != nil {
return "", err
}
return string(bytes), nil
}
func MarshalToString(msg interface{}) (string, error) {
j, e := gojson.Marshal(msg)
if e != nil {
return "", e
}
return string(j), nil
}
func Implode(list interface{}, seq string) string {
listValue := reflect.Indirect(reflect.ValueOf(list))
if listValue.Kind() != reflect.Slice {
return ""
}
count := listValue.Len()
listStr := make([]string, 0, count)
for i := 0; i < count; i++ {
v := listValue.Index(i)
if str, err := getValue(v); err == nil {
listStr = append(listStr, str)
}
}
return strings.Join(listStr, seq)
}
func getValue(value reflect.Value) (res string, err error) {
switch value.Kind() {
case reflect.Ptr:
res, err = getValue(value.Elem())
default:
res = fmt.Sprint(value.Interface())
}
return
}