-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.go
More file actions
118 lines (95 loc) · 2.15 KB
/
Copy pathjson.go
File metadata and controls
118 lines (95 loc) · 2.15 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package json
import (
j "encoding/json"
"fmt"
"errors"
)
type Type int
const (
Object Type = 1
Array Type = 2
String Type = 3
Integer Type = 4
)
type JSON struct {
content interface{}
}
type JSONObject struct {
content map[string]interface{}
}
type JSONArray struct {
content []interface{}
}
func NewJSON(jsonBytes []byte) (json JSON, err error) {
jsonMap, unmarshalError := unmarshallAsJsonObject(jsonBytes)
if unmarshalError == nil {
json = JSON{content: jsonMap,}
return
}
jsonArray, unmarshalError := unmarshallAsJsonArray(jsonBytes)
if unmarshalError == nil {
json = JSON{content: jsonArray,}
return
}
err = fmt.Errorf("failed to unmarshal json :%v", err)
return
}
func unmarshallAsJsonObject(jsonBytes []byte) (json interface{}, err error) {
err = j.Unmarshal(jsonBytes, &json)
if err != nil {
err = fmt.Errorf(fmt.Sprintf("failed to unmarshal json :%v", err))
}
return
}
func unmarshallAsJsonArray(jsonBytes []byte) (json interface{}, err error) {
err = j.Unmarshal(jsonBytes, &json)
if err != nil {
err = fmt.Errorf(fmt.Sprintf("failed to unmarshal json :%v", err))
}
return
}
func (js *JSON) Key(key string) (result interface{}, jsontype Type, err error) {
fmt.Println(fmt.Sprintf("%#v", js.content))
jsMap := js.content
if _, ok := js.content.(map[string]interface{}); ok {
result = jsMap.(map[string]interface{})[key]
jsontype = findType(result)
} else {
err = errors.New("json node not of type object")
}
return result, jsontype, err
}
func (js *JSON) Next(result interface{}) (jsonType Type) {
return
}
func findType(result interface{}) (jsonType Type) {
switch result.(type) {
case string:
jsonType = String
case int:
jsonType = Integer
case float64:
jsonType = Integer
case float32:
jsonType = Integer
case map[string]interface{}:
jsonType = Object
case []interface{}:
jsonType = Array
default:
jsonType = 0
}
return jsonType
}
func checkIfObject(str interface{}) (isObject bool) {
if _, ok := str.(map[string]interface{}); ok {
isObject = true
}
return
}
func checkIfArray(str interface{}) (isArray bool) {
if _, ok := str.([]interface{}); ok {
isArray = true
}
return
}