-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexamples_test.go
More file actions
95 lines (82 loc) · 1.9 KB
/
examples_test.go
File metadata and controls
95 lines (82 loc) · 1.9 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
package jsonry_test
import (
"fmt"
"code.cloudfoundry.org/jsonry"
)
func ExampleMarshal() {
s := struct {
A string
B string `json:"bee,omitempty"`
GUID string `jsonry:"relationships.space.data.guid"`
IDs []int `jsonry:"data.entries[].id"`
}{
A: "foo",
B: "",
GUID: "267758c0-985b-11ea-b9ac-48bf6bec2d78",
IDs: []int{1, 2, 3, 4, 5},
}
json, err := jsonry.Marshal(s)
if err != nil {
panic(err)
}
fmt.Println(string(json))
// Output:
// {"A":"foo","data":{"entries":[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5}]},"relationships":{"space":{"data":{"guid":"267758c0-985b-11ea-b9ac-48bf6bec2d78"}}}}
}
func ExampleMarshal_recursive() {
type s struct {
A string `jsonry:"f"`
}
type t struct {
B []s `jsonry:"d[].e"`
}
type u struct {
C []t `jsonry:"a.b[].c"`
}
data := u{C: []t{{B: []s{{A: "foo"}, {"bar"}}}, {B: []s{{A: "baz"}, {"quz"}}}}}
json, err := jsonry.Marshal(data)
if err != nil {
panic(err)
}
fmt.Println(string(json))
// Output:
// {"a":{"b":[{"c":{"d":[{"e":{"f":"foo"}},{"e":{"f":"bar"}}]}},{"c":{"d":[{"e":{"f":"baz"}},{"e":{"f":"quz"}}]}}]}}
}
func ExampleUnmarshal() {
json := `
{
"A": "foo",
"bee": "bar",
"data": {
"entries": [
{"id": 1},
{"id": 2},
{"id": 3},
{"id": 4},
{"id": 5}
]
},
"relationships": {
"space": {
"data": {
"guid":"267758c0-985b-11ea-b9ac-48bf6bec2d78"}
}
}
}
}`
var s struct {
A string
B string `json:"bee"`
GUID string `jsonry:"relationships.space.data.guid"`
IDs []int `jsonry:"data.entries.id"`
}
if err := jsonry.Unmarshal([]byte(json), &s); err != nil {
panic(err)
}
fmt.Printf("A: %+v\nB: %+v\nGUID: %+v\nIDs: %+v\n", s.A, s.B, s.GUID, s.IDs)
// Output:
// A: foo
// B: bar
// GUID: 267758c0-985b-11ea-b9ac-48bf6bec2d78
// IDs: [1 2 3 4 5]
}