forked from goinggo/mapstructure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapstructure_examples_test.go
323 lines (277 loc) · 8.15 KB
/
mapstructure_examples_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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package mapstructure
import (
"encoding/json"
"fmt"
)
func ExampleDecode() {
type Person struct {
Name string
Age int
Emails []string
Extra map[string]string
}
// This input can come from anywhere, but typically comes from
// something like decoding JSON where we're not quite sure of the
// struct initially.
input := map[string]interface{}{
"name": "Mitchell",
"age": 91,
"emails": []string{"one", "two", "three"},
"extra": map[string]string{
"twitter": "mitchellh",
},
}
var result Person
err := Decode(input, &result)
if err != nil {
panic(err)
}
fmt.Printf("%#v", result)
// Output:
// mapstructure.Person{Name:"Mitchell", Age:91, Emails:[]string{"one", "two", "three"}, Extra:map[string]string{"twitter":"mitchellh"}}
}
func ExampleDecode_errors() {
type Person struct {
Name string
Age int
Emails []string
Extra map[string]string
}
// This input can come from anywhere, but typically comes from
// something like decoding JSON where we're not quite sure of the
// struct initially.
input := map[string]interface{}{
"name": 123,
"age": "bad value",
"emails": []int{1, 2, 3},
}
var result Person
err := Decode(input, &result)
if err == nil {
panic("should have an error")
}
fmt.Println(err.Error())
// Output:
// 5 error(s) decoding:
//
// * 'Name' expected type 'string', got unconvertible type 'int'
// * 'Age' expected type 'int', got unconvertible type 'string'
// * 'Emails[0]' expected type 'string', got unconvertible type 'int'
// * 'Emails[1]' expected type 'string', got unconvertible type 'int'
// * 'Emails[2]' expected type 'string', got unconvertible type 'int'
}
func ExampleDecode_metadata() {
type Person struct {
Name string
Age int
}
// This input can come from anywhere, but typically comes from
// something like decoding JSON where we're not quite sure of the
// struct initially.
input := map[string]interface{}{
"name": "Mitchell",
"age": 91,
"email": "foo@bar.com",
}
// For metadata, we make a more advanced DecoderConfig so we can
// more finely configure the decoder that is used. In this case, we
// just tell the decoder we want to track metadata.
var md Metadata
var result Person
config := &DecoderConfig{
Metadata: &md,
Result: &result,
}
decoder, err := NewDecoder(config)
if err != nil {
panic(err)
}
if err := decoder.Decode(input); err != nil {
panic(err)
}
fmt.Printf("Unused keys: %#v", md.Unused)
// Output:
// Unused keys: []string{"email"}
}
func ExampleDecode_weaklyTypedInput() {
type Person struct {
Name string
Age int
Emails []string
}
// This input can come from anywhere, but typically comes from
// something like decoding JSON, generated by a weakly typed language
// such as PHP.
input := map[string]interface{}{
"name": 123, // number => string
"age": "42", // string => number
"emails": map[string]interface{}{}, // empty map => empty array
}
var result Person
config := &DecoderConfig{
WeaklyTypedInput: true,
Result: &result,
}
decoder, err := NewDecoder(config)
if err != nil {
panic(err)
}
err = decoder.Decode(input)
if err != nil {
panic(err)
}
fmt.Printf("%#v", result)
// Output: mapstructure.Person{Name:"123", Age:42, Emails:[]string{}}
}
func ExampleDecodePath() {
var document string = `{
"userContext": {
"conversationCredentials": {
"sessionToken": "06142010_1:75bf6a413327dd71ebe8f3f30c5a4210a9b11e93c028d6e11abfca7ff"
},
"valid": true,
"isPasswordExpired": false,
"cobrandId": 10000004,
"channelId": -1,
"locale": "en_US",
"tncVersion": 2,
"applicationId": "17CBE222A42161A3FF450E47CF4C1A00",
"cobrandConversationCredentials": {
"sessionToken": "06142010_1:b8d011fefbab8bf1753391b074ffedf9578612d676ed2b7f073b5785b"
},
"preferenceInfo": {
"currencyCode": "USD",
"timeZone": "PST",
"dateFormat": "MM/dd/yyyy",
"currencyNotationType": {
"currencyNotationType": "SYMBOL"
},
"numberFormat": {
"decimalSeparator": ".",
"groupingSeparator": ",",
"groupPattern": "###,##0.##"
}
}
},
"lastLoginTime": 1375686841,
"loginCount": 299,
"passwordRecovered": false,
"emailAddress": "johndoe@email.com",
"loginName": "sptest1",
"userId": 10483860,
"userType":
{
"userTypeId": 1,
"userTypeName": "normal_user"
}
}`
type UserType struct {
UserTypeId int
UserTypeName string
}
type NumberFormat struct {
DecimalSeparator string `jpath:"userContext.preferenceInfo.numberFormat.decimalSeparator"`
GroupingSeparator string `jpath:"userContext.preferenceInfo.numberFormat.groupingSeparator"`
GroupPattern string `jpath:"userContext.preferenceInfo.numberFormat.groupPattern"`
}
type User struct {
Session string `jpath:"userContext.cobrandConversationCredentials.sessionToken"`
CobrandId int `jpath:"userContext.cobrandId"`
UserType UserType `jpath:"userType"`
LoginName string `jpath:"loginName"`
NumberFormat // This can also be a pointer to the struct (*NumberFormat)
}
docScript := []byte(document)
var docMap map[string]interface{}
json.Unmarshal(docScript, &docMap)
var user User
DecodePath(docMap, &user)
fmt.Printf("%#v", user)
// Output:
// mapstructure.User{Session:"06142010_1:b8d011fefbab8bf1753391b074ffedf9578612d676ed2b7f073b5785b", CobrandId:10000004, UserType:mapstructure.UserType{UserTypeId:1, UserTypeName:"normal_user"}, LoginName:"sptest1", NumberFormat:mapstructure.NumberFormat{DecimalSeparator:".", GroupingSeparator:",", GroupPattern:"###,##0.##"}}
}
func ExampleDecodeSlicePath() {
var document = `[{"name":"bill"},{"name":"lisa"}]`
type NameDoc struct {
Name string `jpath:"name"`
}
sliceScript := []byte(document)
var sliceMap []map[string]interface{}
json.Unmarshal(sliceScript, &sliceMap)
var myslice []NameDoc
DecodeSlicePath(sliceMap, &myslice)
fmt.Printf("%#v", myslice)
// Output:
// []mapstructure.NameDoc{mapstructure.NameDoc{Name:"bill"}, mapstructure.NameDoc{Name:"lisa"}}
}
func ExampleDecodeWithEmbeddedSlice() {
var document string = `{
"cobrandId": 10010352,
"channelId": -1,
"locale": "en_US",
"tncVersion": 2,
"categories":["rabbit","bunny","frog"],
"people": [
{
"name": "jack",
"age": {
"birth":10,
"year":2000,
"animals": [
{
"barks":"yes",
"tail":"yes"
},
{
"barks":"no",
"tail":"yes"
}
]
}
},
{
"name": "jill",
"age": {
"birth":11,
"year":2001
}
}
]
}`
type Animal struct {
Barks string `jpath:"barks"`
}
type People struct {
Age int `jpath:"age.birth"` // jpath is relative to the array
Animals []Animal `jpath:"age.animals"`
}
type Items struct {
Categories []string `jpath:"categories"`
Peoples []People `jpath:"people"` // Specify the location of the array
}
docScript := []byte(document)
var docMap map[string]interface{}
json.Unmarshal(docScript, &docMap)
var items Items
DecodePath(docMap, &items)
fmt.Printf("%#v", items)
// Output:
// mapstructure.Items{Categories:[]string{"rabbit", "bunny", "frog"}, Peoples:[]mapstructure.People{mapstructure.People{Age:10, Animals:[]mapstructure.Animal{mapstructure.Animal{Barks:"yes"}, mapstructure.Animal{Barks:"no"}}}, mapstructure.People{Age:11, Animals:[]mapstructure.Animal(nil)}}}
}
func ExampleDecodeWithAbstractField() {
var document = `{"Error":[{"errorDetail":"Invalid Cobrand Credentials"}]}`
type YodleeError struct {
Error []map[string]interface{} `jpath:"Error"`
}
type CobrandContext struct {
YodleeError
}
docScript := []byte(document)
var docMap map[string]interface{}
json.Unmarshal(docScript, &docMap)
var cobrandContext CobrandContext
DecodePath(docMap, &cobrandContext)
fmt.Printf("%#v", cobrandContext)
// Output:
// mapstructure.CobrandContext{YodleeError:mapstructure.YodleeError{Error:[]map[string]interface {}{map[string]interface {}{"errorDetail":"Invalid Cobrand Credentials"}}}}
}