-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsongo.go
114 lines (80 loc) · 2.12 KB
/
jsongo.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
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
package jsongo
import (
"strings"
"strconv"
)
const separator = "."
// If the item is not found, this will be returned
var NotFound string = ""
func Get(query string, json interface{}) string {
var element string
// Get the first separator if it exists (i.e. object.firstItem.subItem)
index := strings.Index(query, separator)
// If there is no separator, get the value of the element
if index == -1 {
return getValue(query, json)
}
element = query[:index]
json = getObject(element, json)
if json == nil {
return NotFound
}
return Get(query[index + 1:], json)
}
func getObject(element string, json interface{}) interface{} {
// Check if the element refers to an array item (i.e. object.firstItem[1])
if strings.Contains(element, "[") {
return getArrayObject(element, json)
}
j, ok := json.(map[string]interface{})
if !ok {
return nil
}
return j[element] //json
}
func getValue(element string, json interface{}) string {
// Check if the element is an array
if strings.Contains(element, "[") {
return getArrayObject(element, json).(string)
}
j, ok := json.(map[string]interface{})
if !ok {
return NotFound
}
value := j[element]
// Check what kind of element we have (string, number) and return it
switch v := value.(type) {
case string:
return v
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
default:
return NotFound
}
return NotFound
}
func getArrayObject(element string, json interface{}) interface{} {
// Get the name of the array
arrayName := element[:strings.Index(element, "[")]
arrayIndexString := element[strings.Index(element, "[")+1:strings.Index(element, "]")]
// Convert the index from string to integer
arrayIndex, err := strconv.Atoi(arrayIndexString)
if err != nil {
panic(err)
}
// Check if the JSON interface is a map
j, ok := json.(map[string]interface{})
if !ok {
return NotFound
}
// Get the array from the JSON if it exists
jsonArray, ok := j[arrayName].([]interface{})
if !ok {
return NotFound
}
// Check if the specified index is within range
if len(jsonArray) <= arrayIndex {
return NotFound
}
return jsonArray[arrayIndex]
}