forked from lestrrat-go/jsref
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsref_example_test.go
52 lines (45 loc) · 1.02 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
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
ptrs := []string{
"#/foo/0", // "bar"
"#/foo/1", // "baz"
"#/foo/2", // "quux" (resolves via `mp`)
"#/foo", // contents of foo key
}
for _, ptr := range ptrs {
result, err := res.Resolve(v, ptr)
if err != nil { // failed to resolve
fmt.Printf("err: %s\n", err)
continue
}
b, _ := json.Marshal(result)
fmt.Printf("%s -> %s\n", ptr, string(b))
}
// OUTPUT:
// #/foo/0 -> "bar"
// #/foo/1 -> "baz"
// #/foo/2 -> "quux"
// #/foo -> ["bar",{"$ref":"#/sub"},{"$ref":"obj2#/sub"}]
}