-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsptr_example_test.go
More file actions
100 lines (85 loc) · 1.76 KB
/
jsptr_example_test.go
File metadata and controls
100 lines (85 loc) · 1.76 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
package jsptr_test
import (
"fmt"
"github.com/lestrrat-go/blackmagic"
"github.com/lestrrat-go/jsptr"
)
type Root struct {
Foo Foo `json:"foo"`
}
type Foo struct {
Bar Bar `json:"bar"`
}
type Bar struct {
Baz string `json:"baz"`
}
type Custom struct{}
func (c *Custom) RetrieveJSONPointer(dst any, ptr string) error {
if ptr == "/foo/bar/baz" {
return blackmagic.AssignIfCompatible(dst, "hello world")
}
return fmt.Errorf("not found")
}
func Example() {
const message = "hello world"
// Retrieve from a map: Useful if you unmarshal a JSON into a map[string]any
m := map[string]any{
"foo": map[string]any{
"bar": map[string]any{
"baz": message,
},
},
}
// Retrieve from a struct: Useful if you unmarshal a JSON into a struct
s := &Root{
Foo: Foo{
Bar: Bar{
Baz: message,
},
},
}
// You could even use a custom target that implements the RetrieveJSONPointer method
custom := &Custom{}
// Or slices
slice := []string{"foo", "bar", "baz", message}
testcases := []struct {
Ptr string
Target any
}{
{
Target: m,
Ptr: "/foo/bar/baz",
},
{
Target: s,
Ptr: "/foo/bar/baz",
},
{
Target: custom,
Ptr: "/foo/bar/baz",
},
{
Target: slice,
Ptr: "/3",
},
}
for _, tc := range testcases {
// Obviously, in real likfe you could (and should) reuse the same pointer if you are
// going to be evaluating the same pointer multiple times.
p, err := jsptr.New(tc.Ptr)
if err != nil {
fmt.Printf("Error creating pointer: %v\n", err)
return
}
var dst string
if err := p.Retrieve(&dst, tc.Target); err != nil {
fmt.Printf("Error retrieving value: %v\n", err)
return
}
if dst != message {
fmt.Printf("Expected 'hello world', got '%s'\n", dst)
return
}
}
// OUTPUT:
}