-
Notifications
You must be signed in to change notification settings - Fork 4
/
json.go
67 lines (52 loc) · 1.58 KB
/
json.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
61
62
63
64
65
66
67
package utils
import (
"encoding/json"
"errors"
)
// EncodeToJSONString encodes inputData to JSON string if it's possible
func EncodeToJSONString(inputData interface{}) string {
result, _ := json.Marshal(inputData)
return string(result)
}
// DecodeJSONToArray decodes json string to []interface{} if it's possible
func DecodeJSONToArray(jsonData interface{}) ([]interface{}, error) {
var result []interface{}
var err error
switch value := jsonData.(type) {
case string:
err = json.Unmarshal([]byte(value), &result)
case []byte:
err = json.Unmarshal(value, &result)
default:
err = errors.New("Unsupported json type for conversion to array")
}
return result, err
}
// DecodeJSONToStringKeyMap decodes json string to map[string]interface{} if it's possible
func DecodeJSONToStringKeyMap(jsonData interface{}) (map[string]interface{}, error) {
result := make(map[string]interface{})
var err error
switch value := jsonData.(type) {
case string:
err = json.Unmarshal([]byte(value), &result)
case []byte:
err = json.Unmarshal(value, &result)
default:
err = errors.New("Unable to create map, unsupported json type")
}
return result, err
}
// DecodeJSONToInterface decodes json string to interface{} if it's possible
func DecodeJSONToInterface(jsonData interface{}) (interface{}, error) {
var result interface{}
var err error
switch value := jsonData.(type) {
case string:
err = json.Unmarshal([]byte(value), &result)
case []byte:
err = json.Unmarshal(value, &result)
default:
err = errors.New("Unable to parse json, unsupported json type")
}
return result, err
}