-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathjsref_example_test.go
69 lines (62 loc) · 1.38 KB
/
jsref_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
package jsref_test
import (
"encoding/json"
"fmt"
"log"
jsref "github.com/lestrrat-go/jsref"
"github.com/lestrrat-go/jsref/provider"
)
func Example() {
var v interface{}
src := []byte(`
{
"foo": ["bar", {"$ref": "#/sub"}, {"$ref": "obj2#/sub"}],
"sub": "baz"
}`)
if err := json.Unmarshal(src, &v); err != nil {
log.Printf("%s", err)
return
}
// External reference
mp := provider.NewMap()
_ = mp.Set("obj2", map[string]string{"sub": "quux"})
res := jsref.New()
_ = res.AddProvider(mp) // Register the provider
data := []struct {
Ptr string
Options []jsref.Option
}{
{
Ptr: "#/foo/0", // "bar"
},
{
Ptr: "#/foo/1", // "baz"
},
{
Ptr: "#/foo/2", // "quux" (resolves via `mp`)
},
{
Ptr: "#/foo", // ["bar",{"$ref":"#/sub"},{"$ref":"obj2#/sub"}]
},
{
Ptr: "#/foo", // ["bar","baz","quux"]
// experimental option to resolve all resulting values
Options: []jsref.Option{ jsref.WithRecursiveResolution(true) },
},
}
for _, set := range data {
result, err := res.Resolve(v, set.Ptr, set.Options...)
if err != nil { // failed to resolve
fmt.Printf("err: %s\n", err)
continue
}
b, _ := json.Marshal(result)
fmt.Printf("%s -> %s\n", set.Ptr, string(b))
}
// OUTPUT:
// #/foo/0 -> "bar"
// #/foo/1 -> "baz"
// #/foo/2 -> "quux"
// #/foo -> ["bar",{"$ref":"#/sub"},{"$ref":"obj2#/sub"}]
// #/foo -> ["bar","baz","quux"]
}