Skip to content

Commit ece4951

Browse files
authored
Merge pull request #2 from lestrrat-go/autodoc-pr-misc
autodoc updates
2 parents 5c07757 + 9509b00 commit ece4951

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

README.md

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,107 @@
33
`github.com/lestrrat-go/jsptr` implements JSON pointers. Currently it only supports retrievals.
44

55
<!-- INCLUDE(./jsptr_example_test.go) -->
6+
```go
7+
package jsptr_test
8+
9+
import (
10+
"fmt"
11+
12+
"github.com/lestrrat-go/blackmagic"
13+
"github.com/lestrrat-go/jsptr"
14+
)
15+
16+
type Root struct {
17+
Foo Foo `json:"foo"`
18+
}
19+
20+
type Foo struct {
21+
Bar Bar `json:"bar"`
22+
}
23+
24+
type Bar struct {
25+
Baz string `json:"baz"`
26+
}
27+
28+
type Custom struct{}
29+
30+
func (c *Custom) RetrieveJSONPointer(dst any, ptr string) error {
31+
if ptr == "/foo/bar/baz" {
32+
return blackmagic.AssignIfCompatible(dst, "hello world")
33+
}
34+
return fmt.Errorf("not found")
35+
}
36+
37+
func Example() {
38+
const message = "hello world"
39+
40+
// Retrieve from a map: Useful if you unmarshal a JSON into a map[string]any
41+
m := map[string]any{
42+
"foo": map[string]any{
43+
"bar": map[string]any{
44+
"baz": message,
45+
},
46+
},
47+
}
48+
49+
// Retrieve from a struct: Useful if you unmarshal a JSON into a struct
50+
s := &Root{
51+
Foo: Foo{
52+
Bar: Bar{
53+
Baz: message,
54+
},
55+
},
56+
}
57+
58+
// You could even use a custom target that implements the RetrieveJSONPointer method
59+
custom := &Custom{}
60+
61+
// Or slices
62+
slice := []string{"foo", "bar", "baz", message}
63+
64+
testcases := []struct {
65+
Ptr string
66+
Target any
67+
}{
68+
{
69+
Target: m,
70+
Ptr: "/foo/bar/baz",
71+
},
72+
{
73+
Target: s,
74+
Ptr: "/foo/bar/baz",
75+
},
76+
{
77+
Target: custom,
78+
Ptr: "/foo/bar/baz",
79+
},
80+
{
81+
Target: slice,
82+
Ptr: "/3",
83+
},
84+
}
85+
for _, tc := range testcases {
86+
// Obviously, in real likfe you could (and should) reuse the same pointer if you are
87+
// going to be evaluating the same pointer multiple times.
88+
p, err := jsptr.New(tc.Ptr)
89+
if err != nil {
90+
fmt.Printf("Error creating pointer: %v\n", err)
91+
return
92+
}
93+
94+
var dst string
95+
if err := p.Retrieve(&dst, tc.Target); err != nil {
96+
fmt.Printf("Error retrieving value: %v\n", err)
97+
return
98+
}
99+
if dst != message {
100+
fmt.Printf("Expected 'hello world', got '%s'\n", dst)
101+
return
102+
}
103+
}
104+
105+
// OUTPUT:
106+
}
107+
```
108+
source: [./jsptr_example_test.go](https://github.com/lestrrat-go/jsptr/blob/v1/./jsptr_example_test.go)
6109
<!-- END INCLUDE -->

0 commit comments

Comments
 (0)