-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
85 lines (69 loc) · 1.83 KB
/
example_test.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
package jsonport
import (
"fmt"
)
func Example_usage() {
jsonstr := `{
"timestamp": "1438194274",
"users": [{"id": 1, "name": "Tom"}, {"id": 2, "name": "Peter"}],
"keywords": ["golang", "json"]
}`
j, _ := Unmarshal([]byte(jsonstr))
// Output: Tom
fmt.Println(j.GetString("users", 0, "name"))
// Output: [golang json]
fmt.Println(j.Get("keywords").StringArray())
// Output: [Tom Peter]
names, _ := j.Get("users").EachOf("name").StringArray()
fmt.Println(names)
// try parse STRING as NUMBER
j.StringAsNumber()
// Output: 1438194274
fmt.Println(j.Get("timestamp").Int())
// convert NUMBER, STRING, ARRAY and OBJECT type to BOOL
j.AllAsBool()
// Output: false
fmt.Println(j.GetBool("status"))
// using Unmarshal with path which can speed up json decode
j, _ = Unmarshal([]byte(jsonstr), "users", 1, "name")
fmt.Println(j.String())
// Output:
// Tom <nil>
// [golang json] <nil>
// [Tom Peter]
// 1438194274 <nil>
// false <nil>
// Peter <nil>
}
func ExampleJson_StringAsNumber() {
jsonstr := `{"timestamp": "1438194274"}`
j, _ := Unmarshal([]byte(jsonstr))
fmt.Println("Without StringAsNumber():")
n, err := j.GetInt("timestamp")
fmt.Println(n, err)
fmt.Println("With StringAsNumber():")
j.StringAsNumber()
n, err = j.GetInt("timestamp")
fmt.Println(n, err)
// Output:
// Without StringAsNumber():
// 0 type mismatch: expected NUMBER, found STRING
// With StringAsNumber():
// 1438194274 <nil>
}
func ExampleJson_AllAsBool() {
jsonstr := `{"enabled": 1}`
j, _ := Unmarshal([]byte(jsonstr))
fmt.Println("Without AllAsBool():")
b, err := j.GetBool("enabled")
fmt.Println(b, err)
fmt.Println("With AllAsBool():")
j.AllAsBool()
b, err = j.GetBool("enabled")
fmt.Println(b, err)
// Output:
// Without AllAsBool():
// false type mismatch: expected BOOL, found NUMBER
// With AllAsBool():
// true <nil>
}