-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample_test.go
107 lines (95 loc) · 1.99 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Copyright 2016-2020 Olivier Mengué. All rights reserved.
// Use of this source code is governed by the Apache 2.0 license that
// can be found in the LICENSE file.
package jsonptr_test
import (
"encoding/json"
"fmt"
"strings"
"testing/iotest"
"github.com/dolmen-go/jsonptr"
)
// Example from https://tools.ietf.org/html/rfc6901#section-5
func Example() {
const JSON = `
{
"foo": ["bar", "baz"],
"": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
}`
var doc interface{}
_ = json.Unmarshal([]byte(JSON), &doc)
for _, ptr := range []string{
"/foo",
"/foo/0",
"/",
"/a~1b",
"/c%d",
"/e^f",
"/g|h",
"/i\\j",
"/k\"l",
"/ ",
"/m~0n",
} {
result, _ := jsonptr.Get(doc, ptr)
fmt.Printf("%-12q %#v\n", ptr, result)
}
// Output:
// "/foo" []interface {}{"bar", "baz"}
// "/foo/0" "bar"
// "/" 0
// "/a~1b" 1
// "/c%d" 2
// "/e^f" 3
// "/g|h" 4
// "/i\\j" 5
// "/k\"l" 6
// "/ " 7
// "/m~0n" 8
}
// ExampleJSONDecoder shows how to extract from a streamed JSON document.
func ExampleJSONDecoder() {
stream := iotest.OneByteReader(strings.NewReader(`{"a": 42,"b":5}`))
decoder := json.NewDecoder(stream)
result, _ := jsonptr.Get(decoder, "/a")
fmt.Println(result)
// Output:
// 42
}
func ExampleSet() {
newArray := []interface{}(nil)
newObject := map[string]interface{}(nil)
var doc interface{}
for _, step := range []struct {
where string
what interface{}
}{
{"", newObject},
{"/arr", newArray},
{"/arr/-", 3},
{"/arr/-", 2},
{"/arr/-", 1},
{"/obj", newObject},
{"/obj/str", "hello"},
{"/obj/bool", true},
{"/arr/-", 0},
{"/obj/", nil},
} {
err := jsonptr.Set(&doc, step.where, step.what)
if err != nil {
panic(err)
}
//fmt.Printf("%#v\n", doc)
}
fmt.Println(func() string { x, _ := json.Marshal(doc); return string(x) }())
// Output:
// {"arr":[3,2,1,0],"obj":{"":null,"bool":true,"str":"hello"}}
}