/
gjson.go
80 lines (73 loc) · 2.35 KB
/
gjson.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
package gjson
import "github.com/tidwall/gjson"
// GetInt returns an integer representation.
func GetInt(json, path string) int64 {
ss := gjson.Get(json, path)
return ss.Int()
}
// GetString returns a string representation of the value.
func GetString(json, path string) string {
ss := gjson.Get(json, path)
return ss.String()
}
// GetInterface returns one of these types:
//
// bool, for JSON booleans
// float64, for JSON numbers
// Number, for JSON numbers
// string, for JSON string literals
// nil, for JSON null
// map[string]interface{}, for JSON objects
// []interface{}, for JSON arrays
//
func GetInterface(json, path string) interface{} {
ss := gjson.Get(json, path)
return ss.Value()
}
// GetBool returns a boolean representation.
func GetBool(json, path string) bool {
ss := gjson.Get(json, path)
return ss.Bool()
}
// GetFloat searches json for the specified path.
// A path is in dot syntax, such as "name.last" or "age".
// When the value is found it's returned immediately.
//
// A path is a series of keys separated by a dot.
// A key may contain special wildcard characters '*' and '?'.
// To access an array value use the index as the key.
// To get the number of elements in an array or to access a child path, use
// the '#' character.
// The dot and wildcard character can be escaped with '\'.
//
// {
// "name": {"first": "Tom", "last": "Anderson"},
// "age":37,
// "children": ["Sara","Alex","Jack"],
// "friends": [
// {"first": "James", "last": "Murphy"},
// {"first": "Roger", "last": "Craig"}
// ]
// }
// "name.last" >> "Anderson"
// "age" >> 37
// "children" >> ["Sara","Alex","Jack"]
// "children.#" >> 3
// "children.1" >> "Alex"
// "child*.2" >> "Jack"
// "c?ildren.0" >> "Sara"
// "friends.#.first" >> ["James","Roger"]
//
// This function expects that the json is well-formed, and does not validate.
// Invalid json will not panic, but it may return unexpected results.
// If you are consuming JSON from an unpredictable source then you may want to
// use the Valid function first.
func GetFloat(json, path string) float64 {
ss := gjson.Get(json, path)
return ss.Float()
}
// GetMap returns a map of values. The result should be a JSON array.
func GetMap(json, path string) map[string]gjson.Result {
ss := gjson.Get(json, path)
return ss.Map()
}