├── LICENSE ├── README.md ├── error.go ├── mapstructure.go ├── mapstructure_benchmark_test.go ├── mapstructure_bugs_test.go ├── mapstructure_examples_test.go └── mapstructure_test.go /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013 Mitchell Hashimoto, William Kennedy 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mapstructure 2 | 3 | mapstructure is a Go library for decoding generic map values to structures 4 | and vice versa, while providing helpful error handling. 5 | 6 | This library is most useful when decoding values from some data stream (JSON, 7 | Gob, etc.) where you don't _quite_ know the structure of the underlying data 8 | until you read a part of it. You can therefore read a `map[string]interface{}` 9 | and use this library to decode it into the proper underlying native Go 10 | structure. 11 | 12 | ## Installation 13 | 14 | Standard `go get`: 15 | 16 | ``` 17 | $ go get github.com/goinggo/mapstructure 18 | ``` 19 | 20 | ## Usage & Example 21 | 22 | For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure). 23 | 24 | The `Decode`, `DecodePath` and `DecodeSlicePath` functions have examples associated with it there. 25 | 26 | ## But Why?! 27 | 28 | Go offers fantastic standard libraries for decoding formats such as JSON. 29 | The standard method is to have a struct pre-created, and populate that struct 30 | from the bytes of the encoded format. This is great, but the problem is if 31 | you have configuration or an encoding that changes slightly depending on 32 | specific fields. For example, consider this JSON: 33 | 34 | ```json 35 | { 36 | "type": "person", 37 | "name": "Mitchell" 38 | } 39 | ``` 40 | 41 | Perhaps we can't populate a specific structure without first reading 42 | the "type" field from the JSON. We could always do two passes over the 43 | decoding of the JSON (reading the "type" first, and the rest later). 44 | However, it is much simpler to just decode this into a `map[string]interface{}` 45 | structure, read the "type" key, then use something like this library 46 | to decode it into the proper structure. 47 | 48 | ## DecodePath 49 | 50 | Sometimes you have a large and complex JSON document where you only need to decode 51 | a small part. 52 | 53 | ``` 54 | { 55 | "userContext": { 56 | "conversationCredentials": { 57 | "sessionToken": "06142010_1:75bf6a413327dd71ebe8f3f30c5a4210a9b11e93c028d6e11abfca7ff" 58 | }, 59 | "valid": true, 60 | "isPasswordExpired": false, 61 | "cobrandId": 10000004, 62 | "channelId": -1, 63 | "locale": "en_US", 64 | "tncVersion": 2, 65 | "applicationId": "17CBE222A42161A3FF450E47CF4C1A00", 66 | "cobrandConversationCredentials": { 67 | "sessionToken": "06142010_1:b8d011fefbab8bf1753391b074ffedf9578612d676ed2b7f073b5785b" 68 | }, 69 | "preferenceInfo": { 70 | "currencyCode": "USD", 71 | "timeZone": "PST", 72 | "dateFormat": "MM/dd/yyyy", 73 | "currencyNotationType": { 74 | "currencyNotationType": "SYMBOL" 75 | }, 76 | "numberFormat": { 77 | "decimalSeparator": ".", 78 | "groupingSeparator": ",", 79 | "groupPattern": "###,##0.##" 80 | } 81 | } 82 | }, 83 | "lastLoginTime": 1375686841, 84 | "loginCount": 299, 85 | "passwordRecovered": false, 86 | "emailAddress": "johndoe@email.com", 87 | "loginName": "sptest1", 88 | "userId": 10483860, 89 | "userType": 90 | { 91 | "userTypeId": 1, 92 | "userTypeName": "normal_user" 93 | } 94 | } 95 | ``` 96 | 97 | It is nice to be able to define and pull the documents and fields you need without 98 | having to map the entire JSON structure. 99 | 100 | ``` 101 | type UserType struct { 102 | UserTypeId int 103 | UserTypeName string 104 | } 105 | 106 | type NumberFormat struct { 107 | DecimalSeparator string `jpath:"userContext.preferenceInfo.numberFormat.decimalSeparator"` 108 | GroupingSeparator string `jpath:"userContext.preferenceInfo.numberFormat.groupingSeparator"` 109 | GroupPattern string `jpath:"userContext.preferenceInfo.numberFormat.groupPattern"` 110 | } 111 | 112 | type User struct { 113 | Session string `jpath:"userContext.cobrandConversationCredentials.sessionToken"` 114 | CobrandId int `jpath:"userContext.cobrandId"` 115 | UserType UserType `jpath:"userType"` 116 | LoginName string `jpath:"loginName"` 117 | NumberFormat // This can also be a pointer to the struct (*NumberFormat) 118 | } 119 | 120 | docScript := []byte(document) 121 | var docMap map[string]interface{} 122 | json.Unmarshal(docScript, &docMap) 123 | 124 | var user User 125 | mapstructure.DecodePath(docMap, &user) 126 | ``` 127 | 128 | ## DecodeSlicePath 129 | 130 | Sometimes you have a slice of documents that you need to decode into a slice of structures 131 | 132 | ``` 133 | [ 134 | {"name":"bill"}, 135 | {"name":"lisa"} 136 | ] 137 | ``` 138 | 139 | Just Unmarshal your document into a slice of maps and decode the slice 140 | 141 | ``` 142 | type NameDoc struct { 143 | Name string `jpath:"name"` 144 | } 145 | 146 | sliceScript := []byte(document) 147 | var sliceMap []map[string]interface{} 148 | json.Unmarshal(sliceScript, &sliceMap) 149 | 150 | var myslice []NameDoc 151 | err := DecodeSlicePath(sliceMap, &myslice) 152 | 153 | var myslice []*NameDoc 154 | err := DecodeSlicePath(sliceMap, &myslice) 155 | ``` 156 | 157 | ## Decode Structs With Embedded Slices 158 | 159 | Sometimes you have a document with arrays 160 | 161 | ``` 162 | { 163 | "cobrandId": 10010352, 164 | "channelId": -1, 165 | "locale": "en_US", 166 | "tncVersion": 2, 167 | "people": [ 168 | { 169 | "name": "jack", 170 | "age": { 171 | "birth":10, 172 | "year":2000, 173 | "animals": [ 174 | { 175 | "barks":"yes", 176 | "tail":"yes" 177 | }, 178 | { 179 | "barks":"no", 180 | "tail":"yes" 181 | } 182 | ] 183 | } 184 | }, 185 | { 186 | "name": "jill", 187 | "age": { 188 | "birth":11, 189 | "year":2001 190 | } 191 | } 192 | ] 193 | } 194 | ``` 195 | 196 | You can decode within those arrays 197 | 198 | ``` 199 | type Animal struct { 200 | Barks string `jpath:"barks"` 201 | } 202 | 203 | type People struct { 204 | Age int `jpath:"age.birth"` // jpath is relative to the array 205 | Animals []Animal `jpath:"age.animals"` 206 | } 207 | 208 | type Items struct { 209 | Categories []string `jpath:"categories"` 210 | Peoples []People `jpath:"people"` // Specify the location of the array 211 | } 212 | 213 | docScript := []byte(document) 214 | var docMap map[string]interface{} 215 | json.Unmarshal(docScript, &docMap) 216 | 217 | var items Items 218 | DecodePath(docMap, &items) 219 | ``` -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | package mapstructure 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | ) 7 | 8 | // Error implements the error interface and can represents multiple 9 | // errors that occur in the course of a single decode. 10 | type Error struct { 11 | Errors []string 12 | } 13 | 14 | func (e *Error) Error() string { 15 | points := make([]string, len(e.Errors)) 16 | for i, err := range e.Errors { 17 | points[i] = fmt.Sprintf("* %s", err) 18 | } 19 | 20 | return fmt.Sprintf( 21 | "%d error(s) decoding:\n\n%s", 22 | len(e.Errors), strings.Join(points, "\n")) 23 | } 24 | 25 | func appendErrors(errors []string, err error) []string { 26 | switch e := err.(type) { 27 | case *Error: 28 | return append(errors, e.Errors...) 29 | default: 30 | return append(errors, e.Error()) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /mapstructure.go: -------------------------------------------------------------------------------- 1 | // The mapstructure package exposes functionality to convert an 2 | // abitrary map[string]interface{} into a native Go structure. 3 | // 4 | // The Go structure can be arbitrarily complex, containing slices, 5 | // other structs, etc. and the decoder will properly decode nested 6 | // maps and so on into the proper structures in the native Go struct. 7 | // See the examples to see what the decoder is capable of. 8 | package mapstructure 9 | 10 | import ( 11 | "errors" 12 | "fmt" 13 | "reflect" 14 | "sort" 15 | "strconv" 16 | "strings" 17 | ) 18 | 19 | type DecodeHookFunc func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) 20 | 21 | // DecoderConfig is the configuration that is used to create a new decoder 22 | // and allows customization of various aspects of decoding. 23 | type DecoderConfig struct { 24 | // DecodeHook, if set, will be called before any decoding and any 25 | // type conversion (if WeaklyTypedInput is on). This lets you modify 26 | // the values before they're set down onto the resulting struct. 27 | // 28 | // If an error is returned, the entire decode will fail with that 29 | // error. 30 | DecodeHook DecodeHookFunc 31 | 32 | // If ErrorUnused is true, then it is an error for there to exist 33 | // keys in the original map that were unused in the decoding process 34 | // (extra keys). 35 | ErrorUnused bool 36 | 37 | // If WeaklyTypedInput is true, the decoder will make the following 38 | // "weak" conversions: 39 | // 40 | // - bools to string (true = "1", false = "0") 41 | // - numbers to string (base 10) 42 | // - bools to int/uint (true = 1, false = 0) 43 | // - strings to int/uint (base implied by prefix) 44 | // - int to bool (true if value != 0) 45 | // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, 46 | // FALSE, false, False. Anything else is an error) 47 | // - empty array = empty map and vice versa 48 | // 49 | WeaklyTypedInput bool 50 | 51 | // Metadata is the struct that will contain extra metadata about 52 | // the decoding. If this is nil, then no metadata will be tracked. 53 | Metadata *Metadata 54 | 55 | // Result is a pointer to the struct that will contain the decoded 56 | // value. 57 | Result interface{} 58 | 59 | // The tag name that mapstructure reads for field names. This 60 | // defaults to "mapstructure" 61 | TagName string 62 | } 63 | 64 | // A Decoder takes a raw interface value and turns it into structured 65 | // data, keeping track of rich error information along the way in case 66 | // anything goes wrong. Unlike the basic top-level Decode method, you can 67 | // more finely control how the Decoder behaves using the DecoderConfig 68 | // structure. The top-level Decode method is just a convenience that sets 69 | // up the most basic Decoder. 70 | type Decoder struct { 71 | config *DecoderConfig 72 | } 73 | 74 | // Metadata contains information about decoding a structure that 75 | // is tedious or difficult to get otherwise. 76 | type Metadata struct { 77 | // Keys are the keys of the structure which were successfully decoded 78 | Keys []string 79 | 80 | // Unused is a slice of keys that were found in the raw value but 81 | // weren't decoded since there was no matching field in the result interface 82 | Unused []string 83 | } 84 | 85 | // Decode takes a map and uses reflection to convert it into the 86 | // given Go native structure. val must be a pointer to a struct. 87 | func Decode(m interface{}, rawVal interface{}) error { 88 | config := &DecoderConfig{ 89 | Metadata: nil, 90 | Result: rawVal, 91 | } 92 | 93 | decoder, err := NewDecoder(config) 94 | if err != nil { 95 | return err 96 | } 97 | 98 | return decoder.Decode(m) 99 | } 100 | 101 | // DecodePath takes a map and uses reflection to convert it into the 102 | // given Go native structure. Tags are used to specify the mapping 103 | // between fields in the map and structure 104 | func DecodePath(m map[string]interface{}, rawVal interface{}) error { 105 | config := &DecoderConfig{ 106 | Metadata: nil, 107 | Result: nil, 108 | } 109 | 110 | decoder, err := NewPathDecoder(config) 111 | if err != nil { 112 | return err 113 | } 114 | 115 | _, err = decoder.DecodePath(m, rawVal) 116 | return err 117 | } 118 | 119 | // DecodeSlicePath decodes a slice of maps against a slice of structures that 120 | // contain specified tags 121 | func DecodeSlicePath(ms []map[string]interface{}, rawSlice interface{}) error { 122 | reflectRawSlice := reflect.TypeOf(rawSlice) 123 | rawKind := reflectRawSlice.Kind() 124 | rawElement := reflectRawSlice.Elem() 125 | 126 | if (rawKind == reflect.Ptr && rawElement.Kind() != reflect.Slice) || 127 | (rawKind != reflect.Ptr && rawKind != reflect.Slice) { 128 | return fmt.Errorf("Incompatible Value, Looking For Slice : %v : %v", rawKind, rawElement.Kind()) 129 | } 130 | 131 | config := &DecoderConfig{ 132 | Metadata: nil, 133 | Result: nil, 134 | } 135 | 136 | decoder, err := NewPathDecoder(config) 137 | if err != nil { 138 | return err 139 | } 140 | 141 | // Create a slice large enough to decode all the values 142 | valSlice := reflect.MakeSlice(rawElement, len(ms), len(ms)) 143 | 144 | // Iterate over the maps and decode each one 145 | for index, m := range ms { 146 | sliceElementType := rawElement.Elem() 147 | if sliceElementType.Kind() != reflect.Ptr { 148 | // A slice of objects 149 | obj := reflect.New(rawElement.Elem()) 150 | decoder.DecodePath(m, reflect.Indirect(obj)) 151 | indexVal := valSlice.Index(index) 152 | indexVal.Set(reflect.Indirect(obj)) 153 | } else { 154 | // A slice of pointers 155 | obj := reflect.New(rawElement.Elem().Elem()) 156 | decoder.DecodePath(m, reflect.Indirect(obj)) 157 | indexVal := valSlice.Index(index) 158 | indexVal.Set(obj) 159 | } 160 | } 161 | 162 | // Set the new slice 163 | reflect.ValueOf(rawSlice).Elem().Set(valSlice) 164 | return nil 165 | } 166 | 167 | // NewDecoder returns a new decoder for the given configuration. Once 168 | // a decoder has been returned, the same configuration must not be used 169 | // again. 170 | func NewDecoder(config *DecoderConfig) (*Decoder, error) { 171 | val := reflect.ValueOf(config.Result) 172 | if val.Kind() != reflect.Ptr { 173 | return nil, errors.New("result must be a pointer") 174 | } 175 | 176 | val = val.Elem() 177 | if !val.CanAddr() { 178 | return nil, errors.New("result must be addressable (a pointer)") 179 | } 180 | 181 | if config.Metadata != nil { 182 | if config.Metadata.Keys == nil { 183 | config.Metadata.Keys = make([]string, 0) 184 | } 185 | 186 | if config.Metadata.Unused == nil { 187 | config.Metadata.Unused = make([]string, 0) 188 | } 189 | } 190 | 191 | if config.TagName == "" { 192 | config.TagName = "mapstructure" 193 | } 194 | 195 | result := &Decoder{ 196 | config: config, 197 | } 198 | 199 | return result, nil 200 | } 201 | 202 | // NewPathDecoder returns a new decoder for the given configuration. 203 | // This is used to decode path specific structures 204 | func NewPathDecoder(config *DecoderConfig) (*Decoder, error) { 205 | if config.Metadata != nil { 206 | if config.Metadata.Keys == nil { 207 | config.Metadata.Keys = make([]string, 0) 208 | } 209 | 210 | if config.Metadata.Unused == nil { 211 | config.Metadata.Unused = make([]string, 0) 212 | } 213 | } 214 | 215 | if config.TagName == "" { 216 | config.TagName = "mapstructure" 217 | } 218 | 219 | result := &Decoder{ 220 | config: config, 221 | } 222 | 223 | return result, nil 224 | } 225 | 226 | // Decode decodes the given raw interface to the target pointer specified 227 | // by the configuration. 228 | func (d *Decoder) Decode(raw interface{}) error { 229 | return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem()) 230 | } 231 | 232 | // DecodePath decodes the raw interface against the map based on the 233 | // specified tags 234 | func (d *Decoder) DecodePath(m map[string]interface{}, rawVal interface{}) (bool, error) { 235 | decoded := false 236 | 237 | var val reflect.Value 238 | reflectRawValue := reflect.ValueOf(rawVal) 239 | kind := reflectRawValue.Kind() 240 | 241 | // Looking for structs and pointers to structs 242 | switch kind { 243 | case reflect.Ptr: 244 | val = reflectRawValue.Elem() 245 | if val.Kind() != reflect.Struct { 246 | return decoded, fmt.Errorf("Incompatible Type : %v : Looking For Struct", kind) 247 | } 248 | case reflect.Struct: 249 | var ok bool 250 | val, ok = rawVal.(reflect.Value) 251 | if ok == false { 252 | return decoded, fmt.Errorf("Incompatible Type : %v : Looking For reflect.Value", kind) 253 | } 254 | default: 255 | return decoded, fmt.Errorf("Incompatible Type : %v", kind) 256 | } 257 | 258 | // Iterate over the fields in the struct 259 | for i := 0; i < val.NumField(); i++ { 260 | valueField := val.Field(i) 261 | typeField := val.Type().Field(i) 262 | tag := typeField.Tag 263 | tagValue := tag.Get("jpath") 264 | 265 | // Is this a field without a tag 266 | if tagValue == "" { 267 | if valueField.Kind() == reflect.Struct { 268 | // We have a struct that may have indivdual tags. Process separately 269 | d.DecodePath(m, valueField) 270 | continue 271 | } else if valueField.Kind() == reflect.Ptr && reflect.TypeOf(valueField).Kind() == reflect.Struct { 272 | // We have a pointer to a struct 273 | if valueField.IsNil() { 274 | // Create the object since it doesn't exist 275 | valueField.Set(reflect.New(valueField.Type().Elem())) 276 | decoded, _ = d.DecodePath(m, valueField.Elem()) 277 | if decoded == false { 278 | // If nothing was decoded for this object return the pointer to nil 279 | valueField.Set(reflect.NewAt(valueField.Type().Elem(), nil)) 280 | } 281 | continue 282 | } 283 | 284 | d.DecodePath(m, valueField.Elem()) 285 | continue 286 | } 287 | } 288 | 289 | // Use mapstructure to populate the fields 290 | keys := strings.Split(tagValue, ".") 291 | data := d.findData(m, keys) 292 | if data != nil { 293 | if valueField.Kind() == reflect.Slice { 294 | // Ignore a slice of maps - This sucks but not sure how to check 295 | if strings.Contains(valueField.Type().String(), "map[") { 296 | goto normal_decode 297 | } 298 | 299 | // We have a slice 300 | mapSlice := data.([]interface{}) 301 | if len(mapSlice) > 0 { 302 | // Test if this is a slice of more maps 303 | _, ok := mapSlice[0].(map[string]interface{}) 304 | if ok == false { 305 | goto normal_decode 306 | } 307 | 308 | // Extract the maps out and run it through DecodeSlicePath 309 | ms := make([]map[string]interface{}, len(mapSlice)) 310 | for index, m2 := range mapSlice { 311 | ms[index] = m2.(map[string]interface{}) 312 | } 313 | 314 | DecodeSlicePath(ms, valueField.Addr().Interface()) 315 | continue 316 | } 317 | } 318 | normal_decode: 319 | decoded = true 320 | err := d.decode("", data, valueField) 321 | if err != nil { 322 | return false, err 323 | } 324 | } 325 | } 326 | 327 | return decoded, nil 328 | } 329 | 330 | // Decodes an unknown data type into a specific reflection value. 331 | func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error { 332 | if data == nil { 333 | // If the data is nil, then we don't set anything. 334 | return nil 335 | } 336 | 337 | dataVal := reflect.ValueOf(data) 338 | if !dataVal.IsValid() { 339 | // If the data value is invalid, then we just set the value 340 | // to be the zero value. 341 | val.Set(reflect.Zero(val.Type())) 342 | return nil 343 | } 344 | 345 | if d.config.DecodeHook != nil { 346 | // We have a DecodeHook, so let's pre-process the data. 347 | var err error 348 | data, err = d.config.DecodeHook(d.getKind(dataVal), d.getKind(val), data) 349 | if err != nil { 350 | return err 351 | } 352 | } 353 | 354 | var err error 355 | dataKind := d.getKind(val) 356 | switch dataKind { 357 | case reflect.Bool: 358 | err = d.decodeBool(name, data, val) 359 | case reflect.Interface: 360 | err = d.decodeBasic(name, data, val) 361 | case reflect.String: 362 | err = d.decodeString(name, data, val) 363 | case reflect.Int: 364 | err = d.decodeInt(name, data, val) 365 | case reflect.Uint: 366 | err = d.decodeUint(name, data, val) 367 | case reflect.Float32: 368 | err = d.decodeFloat(name, data, val) 369 | case reflect.Struct: 370 | err = d.decodeStruct(name, data, val) 371 | case reflect.Map: 372 | err = d.decodeMap(name, data, val) 373 | case reflect.Slice: 374 | err = d.decodeSlice(name, data, val) 375 | default: 376 | // If we reached this point then we weren't able to decode it 377 | return fmt.Errorf("%s: unsupported type: %s", name, dataKind) 378 | } 379 | 380 | // If we reached here, then we successfully decoded SOMETHING, so 381 | // mark the key as used if we're tracking metadata. 382 | if d.config.Metadata != nil && name != "" { 383 | d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) 384 | } 385 | 386 | return err 387 | } 388 | 389 | // findData locates the data by walking the keys down the map 390 | func (d *Decoder) findData(m map[string]interface{}, keys []string) interface{} { 391 | if len(keys) == 1 { 392 | if value, ok := m[keys[0]]; ok == true { 393 | return value 394 | } 395 | return nil 396 | } 397 | 398 | if value, ok := m[keys[0]]; ok == true { 399 | if m, ok := value.(map[string]interface{}); ok == true { 400 | return d.findData(m, keys[1:]) 401 | } 402 | } 403 | 404 | return nil 405 | } 406 | 407 | func (d *Decoder) getKind(val reflect.Value) reflect.Kind { 408 | kind := val.Kind() 409 | 410 | switch { 411 | case kind >= reflect.Int && kind <= reflect.Int64: 412 | return reflect.Int 413 | case kind >= reflect.Uint && kind <= reflect.Uint64: 414 | return reflect.Uint 415 | case kind >= reflect.Float32 && kind <= reflect.Float64: 416 | return reflect.Float32 417 | default: 418 | return kind 419 | } 420 | } 421 | 422 | // This decodes a basic type (bool, int, string, etc.) and sets the 423 | // value to "data" of that type. 424 | func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { 425 | dataVal := reflect.ValueOf(data) 426 | dataValType := dataVal.Type() 427 | if !dataValType.AssignableTo(val.Type()) { 428 | return fmt.Errorf( 429 | "'%s' expected type '%s', got '%s'", 430 | name, val.Type(), dataValType) 431 | } 432 | 433 | val.Set(dataVal) 434 | return nil 435 | } 436 | 437 | func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { 438 | dataVal := reflect.ValueOf(data) 439 | dataKind := d.getKind(dataVal) 440 | 441 | switch { 442 | case dataKind == reflect.String: 443 | val.SetString(dataVal.String()) 444 | case dataKind == reflect.Bool && d.config.WeaklyTypedInput: 445 | if dataVal.Bool() { 446 | val.SetString("1") 447 | } else { 448 | val.SetString("0") 449 | } 450 | case dataKind == reflect.Int && d.config.WeaklyTypedInput: 451 | val.SetString(strconv.FormatInt(dataVal.Int(), 10)) 452 | case dataKind == reflect.Uint && d.config.WeaklyTypedInput: 453 | val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) 454 | case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: 455 | val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) 456 | default: 457 | return fmt.Errorf( 458 | "'%s' expected type '%s', got unconvertible type '%s'", 459 | name, val.Type(), dataVal.Type()) 460 | } 461 | 462 | return nil 463 | } 464 | 465 | func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { 466 | dataVal := reflect.ValueOf(data) 467 | dataKind := d.getKind(dataVal) 468 | 469 | switch { 470 | case dataKind == reflect.Int: 471 | val.SetInt(dataVal.Int()) 472 | case dataKind == reflect.Uint: 473 | val.SetInt(int64(dataVal.Uint())) 474 | case dataKind == reflect.Float32: 475 | val.SetInt(int64(dataVal.Float())) 476 | case dataKind == reflect.Bool && d.config.WeaklyTypedInput: 477 | if dataVal.Bool() { 478 | val.SetInt(1) 479 | } else { 480 | val.SetInt(0) 481 | } 482 | case dataKind == reflect.String && d.config.WeaklyTypedInput: 483 | i, err := strconv.ParseInt(dataVal.String(), 0, val.Type().Bits()) 484 | if err == nil { 485 | val.SetInt(i) 486 | } else { 487 | return fmt.Errorf("cannot parse '%s' as int: %s", name, err) 488 | } 489 | default: 490 | return fmt.Errorf( 491 | "'%s' expected type '%s', got unconvertible type '%s'", 492 | name, val.Type(), dataVal.Type()) 493 | } 494 | 495 | return nil 496 | } 497 | 498 | func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { 499 | dataVal := reflect.ValueOf(data) 500 | dataKind := d.getKind(dataVal) 501 | 502 | switch { 503 | case dataKind == reflect.Int: 504 | val.SetUint(uint64(dataVal.Int())) 505 | case dataKind == reflect.Uint: 506 | val.SetUint(dataVal.Uint()) 507 | case dataKind == reflect.Float32: 508 | val.SetUint(uint64(dataVal.Float())) 509 | case dataKind == reflect.Bool && d.config.WeaklyTypedInput: 510 | if dataVal.Bool() { 511 | val.SetUint(1) 512 | } else { 513 | val.SetUint(0) 514 | } 515 | case dataKind == reflect.String && d.config.WeaklyTypedInput: 516 | i, err := strconv.ParseUint(dataVal.String(), 0, val.Type().Bits()) 517 | if err == nil { 518 | val.SetUint(i) 519 | } else { 520 | return fmt.Errorf("cannot parse '%s' as uint: %s", name, err) 521 | } 522 | default: 523 | return fmt.Errorf( 524 | "'%s' expected type '%s', got unconvertible type '%s'", 525 | name, val.Type(), dataVal.Type()) 526 | } 527 | 528 | return nil 529 | } 530 | 531 | func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { 532 | dataVal := reflect.ValueOf(data) 533 | dataKind := d.getKind(dataVal) 534 | 535 | switch { 536 | case dataKind == reflect.Bool: 537 | val.SetBool(dataVal.Bool()) 538 | case dataKind == reflect.Int && d.config.WeaklyTypedInput: 539 | val.SetBool(dataVal.Int() != 0) 540 | case dataKind == reflect.Uint && d.config.WeaklyTypedInput: 541 | val.SetBool(dataVal.Uint() != 0) 542 | case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: 543 | val.SetBool(dataVal.Float() != 0) 544 | case dataKind == reflect.String && d.config.WeaklyTypedInput: 545 | b, err := strconv.ParseBool(dataVal.String()) 546 | if err == nil { 547 | val.SetBool(b) 548 | } else if dataVal.String() == "" { 549 | val.SetBool(false) 550 | } else { 551 | return fmt.Errorf("cannot parse '%s' as bool: %s", name, err) 552 | } 553 | default: 554 | return fmt.Errorf( 555 | "'%s' expected type '%s', got unconvertible type '%s'", 556 | name, val.Type(), dataVal.Type()) 557 | } 558 | 559 | return nil 560 | } 561 | 562 | func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { 563 | dataVal := reflect.ValueOf(data) 564 | dataKind := d.getKind(dataVal) 565 | 566 | switch { 567 | case dataKind == reflect.Int: 568 | val.SetFloat(float64(dataVal.Int())) 569 | case dataKind == reflect.Uint: 570 | val.SetFloat(float64(dataVal.Uint())) 571 | case dataKind == reflect.Float32: 572 | val.SetFloat(float64(dataVal.Float())) 573 | case dataKind == reflect.Bool && d.config.WeaklyTypedInput: 574 | if dataVal.Bool() { 575 | val.SetFloat(1) 576 | } else { 577 | val.SetFloat(0) 578 | } 579 | case dataKind == reflect.String && d.config.WeaklyTypedInput: 580 | f, err := strconv.ParseFloat(dataVal.String(), val.Type().Bits()) 581 | if err == nil { 582 | val.SetFloat(f) 583 | } else { 584 | return fmt.Errorf("cannot parse '%s' as float: %s", name, err) 585 | } 586 | default: 587 | return fmt.Errorf( 588 | "'%s' expected type '%s', got unconvertible type '%s'", 589 | name, val.Type(), dataVal.Type()) 590 | } 591 | 592 | return nil 593 | } 594 | 595 | func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { 596 | valType := val.Type() 597 | valKeyType := valType.Key() 598 | valElemType := valType.Elem() 599 | 600 | // Make a new map to hold our result 601 | mapType := reflect.MapOf(valKeyType, valElemType) 602 | valMap := reflect.MakeMap(mapType) 603 | 604 | // Check input type 605 | dataVal := reflect.Indirect(reflect.ValueOf(data)) 606 | if dataVal.Kind() != reflect.Map { 607 | // Accept empty array/slice instead of an empty map in weakly typed mode 608 | if d.config.WeaklyTypedInput && 609 | (dataVal.Kind() == reflect.Slice || dataVal.Kind() == reflect.Array) && 610 | dataVal.Len() == 0 { 611 | val.Set(valMap) 612 | return nil 613 | } else { 614 | return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) 615 | } 616 | } 617 | 618 | // Accumulate errors 619 | errors := make([]string, 0) 620 | 621 | for _, k := range dataVal.MapKeys() { 622 | fieldName := fmt.Sprintf("%s[%s]", name, k) 623 | 624 | // First decode the key into the proper type 625 | currentKey := reflect.Indirect(reflect.New(valKeyType)) 626 | if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { 627 | errors = appendErrors(errors, err) 628 | continue 629 | } 630 | 631 | // Next decode the data into the proper type 632 | v := dataVal.MapIndex(k).Interface() 633 | currentVal := reflect.Indirect(reflect.New(valElemType)) 634 | if err := d.decode(fieldName, v, currentVal); err != nil { 635 | errors = appendErrors(errors, err) 636 | continue 637 | } 638 | 639 | valMap.SetMapIndex(currentKey, currentVal) 640 | } 641 | 642 | // Set the built up map to the value 643 | val.Set(valMap) 644 | 645 | // If we had errors, return those 646 | if len(errors) > 0 { 647 | return &Error{errors} 648 | } 649 | 650 | return nil 651 | } 652 | 653 | func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { 654 | dataVal := reflect.Indirect(reflect.ValueOf(data)) 655 | dataValKind := dataVal.Kind() 656 | valType := val.Type() 657 | valElemType := valType.Elem() 658 | 659 | // Make a new slice to hold our result, same size as the original data. 660 | sliceType := reflect.SliceOf(valElemType) 661 | valSlice := reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) 662 | 663 | // Check input type 664 | if dataValKind != reflect.Array && dataValKind != reflect.Slice { 665 | // Accept empty map instead of array/slice in weakly typed mode 666 | if d.config.WeaklyTypedInput && dataVal.Kind() == reflect.Map && dataVal.Len() == 0 { 667 | val.Set(valSlice) 668 | return nil 669 | } else { 670 | return fmt.Errorf( 671 | "'%s': source data must be an array or slice, got %s", name, dataValKind) 672 | } 673 | } 674 | 675 | // Accumulate any errors 676 | errors := make([]string, 0) 677 | 678 | for i := 0; i < dataVal.Len(); i++ { 679 | currentData := dataVal.Index(i).Interface() 680 | currentField := valSlice.Index(i) 681 | 682 | fieldName := fmt.Sprintf("%s[%d]", name, i) 683 | if err := d.decode(fieldName, currentData, currentField); err != nil { 684 | errors = appendErrors(errors, err) 685 | } 686 | } 687 | 688 | // Finally, set the value to the slice we built up 689 | val.Set(valSlice) 690 | 691 | // If there were errors, we return those 692 | if len(errors) > 0 { 693 | return &Error{errors} 694 | } 695 | 696 | return nil 697 | } 698 | 699 | func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { 700 | dataVal := reflect.Indirect(reflect.ValueOf(data)) 701 | dataValKind := dataVal.Kind() 702 | if dataValKind != reflect.Map { 703 | return fmt.Errorf("'%s' expected a map, got '%s'", name, dataValKind) 704 | } 705 | 706 | dataValType := dataVal.Type() 707 | if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface { 708 | return fmt.Errorf( 709 | "'%s' needs a map with string keys, has '%s' keys", 710 | name, dataValType.Key().Kind()) 711 | } 712 | 713 | dataValKeys := make(map[reflect.Value]struct{}) 714 | dataValKeysUnused := make(map[interface{}]struct{}) 715 | for _, dataValKey := range dataVal.MapKeys() { 716 | dataValKeys[dataValKey] = struct{}{} 717 | dataValKeysUnused[dataValKey.Interface()] = struct{}{} 718 | } 719 | 720 | errors := make([]string, 0) 721 | 722 | // This slice will keep track of all the structs we'll be decoding. 723 | // There can be more than one struct if there are embedded structs 724 | // that are squashed. 725 | structs := make([]reflect.Value, 1, 5) 726 | structs[0] = val 727 | 728 | // Compile the list of all the fields that we're going to be decoding 729 | // from all the structs. 730 | fields := make(map[*reflect.StructField]reflect.Value) 731 | for len(structs) > 0 { 732 | structVal := structs[0] 733 | structs = structs[1:] 734 | 735 | structType := structVal.Type() 736 | for i := 0; i < structType.NumField(); i++ { 737 | fieldType := structType.Field(i) 738 | 739 | if fieldType.Anonymous { 740 | fieldKind := fieldType.Type.Kind() 741 | if fieldKind != reflect.Struct { 742 | errors = appendErrors(errors, 743 | fmt.Errorf("%s: unsupported type: %s", fieldType.Name, fieldKind)) 744 | continue 745 | } 746 | 747 | // We have an embedded field. We "squash" the fields down 748 | // if specified in the tag. 749 | squash := false 750 | tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") 751 | for _, tag := range tagParts[1:] { 752 | if tag == "squash" { 753 | squash = true 754 | break 755 | } 756 | } 757 | 758 | if squash { 759 | structs = append(structs, val.FieldByName(fieldType.Name)) 760 | continue 761 | } 762 | } 763 | 764 | // Normal struct field, store it away 765 | fields[&fieldType] = structVal.Field(i) 766 | } 767 | } 768 | 769 | for fieldType, field := range fields { 770 | fieldName := fieldType.Name 771 | 772 | tagValue := fieldType.Tag.Get(d.config.TagName) 773 | tagValue = strings.SplitN(tagValue, ",", 2)[0] 774 | if tagValue != "" { 775 | fieldName = tagValue 776 | } 777 | 778 | rawMapKey := reflect.ValueOf(fieldName) 779 | rawMapVal := dataVal.MapIndex(rawMapKey) 780 | if !rawMapVal.IsValid() { 781 | // Do a slower search by iterating over each key and 782 | // doing case-insensitive search. 783 | for dataValKey, _ := range dataValKeys { 784 | mK, ok := dataValKey.Interface().(string) 785 | if !ok { 786 | // Not a string key 787 | continue 788 | } 789 | 790 | if strings.EqualFold(mK, fieldName) { 791 | rawMapKey = dataValKey 792 | rawMapVal = dataVal.MapIndex(dataValKey) 793 | break 794 | } 795 | } 796 | 797 | if !rawMapVal.IsValid() { 798 | // There was no matching key in the map for the value in 799 | // the struct. Just ignore. 800 | continue 801 | } 802 | } 803 | 804 | // Delete the key we're using from the unused map so we stop tracking 805 | delete(dataValKeysUnused, rawMapKey.Interface()) 806 | 807 | if !field.IsValid() { 808 | // This should never happen 809 | panic("field is not valid") 810 | } 811 | 812 | // If we can't set the field, then it is unexported or something, 813 | // and we just continue onwards. 814 | if !field.CanSet() { 815 | continue 816 | } 817 | 818 | // If the name is empty string, then we're at the root, and we 819 | // don't dot-join the fields. 820 | if name != "" { 821 | fieldName = fmt.Sprintf("%s.%s", name, fieldName) 822 | } 823 | 824 | if err := d.decode(fieldName, rawMapVal.Interface(), field); err != nil { 825 | errors = appendErrors(errors, err) 826 | } 827 | } 828 | 829 | if d.config.ErrorUnused && len(dataValKeysUnused) > 0 { 830 | keys := make([]string, 0, len(dataValKeysUnused)) 831 | for rawKey, _ := range dataValKeysUnused { 832 | keys = append(keys, rawKey.(string)) 833 | } 834 | sort.Strings(keys) 835 | 836 | err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", ")) 837 | errors = appendErrors(errors, err) 838 | } 839 | 840 | if len(errors) > 0 { 841 | return &Error{errors} 842 | } 843 | 844 | // Add the unused keys to the list of unused keys if we're tracking metadata 845 | if d.config.Metadata != nil { 846 | for rawKey, _ := range dataValKeysUnused { 847 | key := rawKey.(string) 848 | if name != "" { 849 | key = fmt.Sprintf("%s.%s", name, key) 850 | } 851 | 852 | d.config.Metadata.Unused = append(d.config.Metadata.Unused, key) 853 | } 854 | } 855 | 856 | return nil 857 | } 858 | -------------------------------------------------------------------------------- /mapstructure_benchmark_test.go: -------------------------------------------------------------------------------- 1 | package mapstructure 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Benchmark_Decode(b *testing.B) { 8 | type Person struct { 9 | Name string 10 | Age int 11 | Emails []string 12 | Extra map[string]string 13 | } 14 | 15 | input := map[string]interface{}{ 16 | "name": "Mitchell", 17 | "age": 91, 18 | "emails": []string{"one", "two", "three"}, 19 | "extra": map[string]string{ 20 | "twitter": "mitchellh", 21 | }, 22 | } 23 | 24 | var result Person 25 | for i := 0; i < b.N; i++ { 26 | Decode(input, &result) 27 | } 28 | } 29 | 30 | func Benchmark_DecodeBasic(b *testing.B) { 31 | input := map[string]interface{}{ 32 | "vstring": "foo", 33 | "vint": 42, 34 | "Vuint": 42, 35 | "vbool": true, 36 | "Vfloat": 42.42, 37 | "vsilent": true, 38 | "vdata": 42, 39 | } 40 | 41 | var result Basic 42 | for i := 0; i < b.N; i++ { 43 | Decode(input, &result) 44 | } 45 | } 46 | 47 | func Benchmark_DecodeEmbedded(b *testing.B) { 48 | input := map[string]interface{}{ 49 | "vstring": "foo", 50 | "Basic": map[string]interface{}{ 51 | "vstring": "innerfoo", 52 | }, 53 | "vunique": "bar", 54 | } 55 | 56 | var result Embedded 57 | for i := 0; i < b.N; i++ { 58 | Decode(input, &result) 59 | } 60 | } 61 | 62 | func Benchmark_DecodeTypeConversion(b *testing.B) { 63 | input := map[string]interface{}{ 64 | "IntToFloat": 42, 65 | "IntToUint": 42, 66 | "IntToBool": 1, 67 | "IntToString": 42, 68 | "UintToInt": 42, 69 | "UintToFloat": 42, 70 | "UintToBool": 42, 71 | "UintToString": 42, 72 | "BoolToInt": true, 73 | "BoolToUint": true, 74 | "BoolToFloat": true, 75 | "BoolToString": true, 76 | "FloatToInt": 42.42, 77 | "FloatToUint": 42.42, 78 | "FloatToBool": 42.42, 79 | "FloatToString": 42.42, 80 | "StringToInt": "42", 81 | "StringToUint": "42", 82 | "StringToBool": "1", 83 | "StringToFloat": "42.42", 84 | "SliceToMap": []interface{}{}, 85 | "MapToSlice": map[string]interface{}{}, 86 | } 87 | 88 | var resultStrict TypeConversionResult 89 | for i := 0; i < b.N; i++ { 90 | Decode(input, &resultStrict) 91 | } 92 | } 93 | 94 | func Benchmark_DecodeMap(b *testing.B) { 95 | input := map[string]interface{}{ 96 | "vfoo": "foo", 97 | "vother": map[interface{}]interface{}{ 98 | "foo": "foo", 99 | "bar": "bar", 100 | }, 101 | } 102 | 103 | var result Map 104 | for i := 0; i < b.N; i++ { 105 | Decode(input, &result) 106 | } 107 | } 108 | 109 | func Benchmark_DecodeMapOfStruct(b *testing.B) { 110 | input := map[string]interface{}{ 111 | "value": map[string]interface{}{ 112 | "foo": map[string]string{"vstring": "one"}, 113 | "bar": map[string]string{"vstring": "two"}, 114 | }, 115 | } 116 | 117 | var result MapOfStruct 118 | for i := 0; i < b.N; i++ { 119 | Decode(input, &result) 120 | } 121 | } 122 | 123 | func Benchmark_DecodeSlice(b *testing.B) { 124 | input := map[string]interface{}{ 125 | "vfoo": "foo", 126 | "vbar": []string{"foo", "bar", "baz"}, 127 | } 128 | 129 | var result Slice 130 | for i := 0; i < b.N; i++ { 131 | Decode(input, &result) 132 | } 133 | } 134 | 135 | func Benchmark_DecodeSliceOfStruct(b *testing.B) { 136 | input := map[string]interface{}{ 137 | "value": []map[string]interface{}{ 138 | {"vstring": "one"}, 139 | {"vstring": "two"}, 140 | }, 141 | } 142 | 143 | var result SliceOfStruct 144 | for i := 0; i < b.N; i++ { 145 | Decode(input, &result) 146 | } 147 | } 148 | 149 | func Benchmark_DecodeWeaklyTypedInput(b *testing.B) { 150 | type Person struct { 151 | Name string 152 | Age int 153 | Emails []string 154 | } 155 | 156 | // This input can come from anywhere, but typically comes from 157 | // something like decoding JSON, generated by a weakly typed language 158 | // such as PHP. 159 | input := map[string]interface{}{ 160 | "name": 123, // number => string 161 | "age": "42", // string => number 162 | "emails": map[string]interface{}{}, // empty map => empty array 163 | } 164 | 165 | var result Person 166 | config := &DecoderConfig{ 167 | WeaklyTypedInput: true, 168 | Result: &result, 169 | } 170 | 171 | decoder, err := NewDecoder(config) 172 | if err != nil { 173 | panic(err) 174 | } 175 | 176 | for i := 0; i < b.N; i++ { 177 | decoder.Decode(input) 178 | } 179 | } 180 | 181 | func Benchmark_DecodeMetadata(b *testing.B) { 182 | type Person struct { 183 | Name string 184 | Age int 185 | } 186 | 187 | input := map[string]interface{}{ 188 | "name": "Mitchell", 189 | "age": 91, 190 | "email": "foo@bar.com", 191 | } 192 | 193 | var md Metadata 194 | var result Person 195 | config := &DecoderConfig{ 196 | Metadata: &md, 197 | Result: &result, 198 | } 199 | 200 | decoder, err := NewDecoder(config) 201 | if err != nil { 202 | panic(err) 203 | } 204 | 205 | for i := 0; i < b.N; i++ { 206 | decoder.Decode(input) 207 | } 208 | } 209 | 210 | func Benchmark_DecodeMetadataEmbedded(b *testing.B) { 211 | input := map[string]interface{}{ 212 | "vstring": "foo", 213 | "vunique": "bar", 214 | } 215 | 216 | var md Metadata 217 | var result EmbeddedSquash 218 | config := &DecoderConfig{ 219 | Metadata: &md, 220 | Result: &result, 221 | } 222 | 223 | decoder, err := NewDecoder(config) 224 | if err != nil { 225 | b.Fatalf("err: %s", err) 226 | } 227 | 228 | for i := 0; i < b.N; i++ { 229 | decoder.Decode(input) 230 | } 231 | } 232 | 233 | func Benchmark_DecodeTagged(b *testing.B) { 234 | input := map[string]interface{}{ 235 | "foo": "bar", 236 | "bar": "value", 237 | } 238 | 239 | var result Tagged 240 | for i := 0; i < b.N; i++ { 241 | Decode(input, &result) 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /mapstructure_bugs_test.go: -------------------------------------------------------------------------------- 1 | package mapstructure 2 | 3 | import "testing" 4 | 5 | // GH-1 6 | func TestDecode_NilValue(t *testing.T) { 7 | input := map[string]interface{}{ 8 | "vfoo": nil, 9 | "vother": nil, 10 | } 11 | 12 | var result Map 13 | err := Decode(input, &result) 14 | if err != nil { 15 | t.Fatalf("should not error: %s", err) 16 | } 17 | 18 | if result.Vfoo != "" { 19 | t.Fatalf("value should be default: %s", result.Vfoo) 20 | } 21 | 22 | if result.Vother != nil { 23 | t.Fatalf("Vother should be nil: %s", result.Vother) 24 | } 25 | } 26 | 27 | // GH-10 28 | func TestDecode_mapInterfaceInterface(t *testing.T) { 29 | input := map[interface{}]interface{}{ 30 | "vfoo": nil, 31 | "vother": nil, 32 | } 33 | 34 | var result Map 35 | err := Decode(input, &result) 36 | if err != nil { 37 | t.Fatalf("should not error: %s", err) 38 | } 39 | 40 | if result.Vfoo != "" { 41 | t.Fatalf("value should be default: %s", result.Vfoo) 42 | } 43 | 44 | if result.Vother != nil { 45 | t.Fatalf("Vother should be nil: %s", result.Vother) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /mapstructure_examples_test.go: -------------------------------------------------------------------------------- 1 | package mapstructure 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | func ExampleDecode() { 9 | type Person struct { 10 | Name string 11 | Age int 12 | Emails []string 13 | Extra map[string]string 14 | } 15 | 16 | // This input can come from anywhere, but typically comes from 17 | // something like decoding JSON where we're not quite sure of the 18 | // struct initially. 19 | input := map[string]interface{}{ 20 | "name": "Mitchell", 21 | "age": 91, 22 | "emails": []string{"one", "two", "three"}, 23 | "extra": map[string]string{ 24 | "twitter": "mitchellh", 25 | }, 26 | } 27 | 28 | var result Person 29 | err := Decode(input, &result) 30 | if err != nil { 31 | panic(err) 32 | } 33 | 34 | fmt.Printf("%#v", result) 35 | // Output: 36 | // mapstructure.Person{Name:"Mitchell", Age:91, Emails:[]string{"one", "two", "three"}, Extra:map[string]string{"twitter":"mitchellh"}} 37 | } 38 | 39 | func ExampleDecode_errors() { 40 | type Person struct { 41 | Name string 42 | Age int 43 | Emails []string 44 | Extra map[string]string 45 | } 46 | 47 | // This input can come from anywhere, but typically comes from 48 | // something like decoding JSON where we're not quite sure of the 49 | // struct initially. 50 | input := map[string]interface{}{ 51 | "name": 123, 52 | "age": "bad value", 53 | "emails": []int{1, 2, 3}, 54 | } 55 | 56 | var result Person 57 | err := Decode(input, &result) 58 | if err == nil { 59 | panic("should have an error") 60 | } 61 | 62 | fmt.Println(err.Error()) 63 | // Output: 64 | // 5 error(s) decoding: 65 | // 66 | // * 'Name' expected type 'string', got unconvertible type 'int' 67 | // * 'Age' expected type 'int', got unconvertible type 'string' 68 | // * 'Emails[0]' expected type 'string', got unconvertible type 'int' 69 | // * 'Emails[1]' expected type 'string', got unconvertible type 'int' 70 | // * 'Emails[2]' expected type 'string', got unconvertible type 'int' 71 | } 72 | 73 | func ExampleDecode_metadata() { 74 | type Person struct { 75 | Name string 76 | Age int 77 | } 78 | 79 | // This input can come from anywhere, but typically comes from 80 | // something like decoding JSON where we're not quite sure of the 81 | // struct initially. 82 | input := map[string]interface{}{ 83 | "name": "Mitchell", 84 | "age": 91, 85 | "email": "foo@bar.com", 86 | } 87 | 88 | // For metadata, we make a more advanced DecoderConfig so we can 89 | // more finely configure the decoder that is used. In this case, we 90 | // just tell the decoder we want to track metadata. 91 | var md Metadata 92 | var result Person 93 | config := &DecoderConfig{ 94 | Metadata: &md, 95 | Result: &result, 96 | } 97 | 98 | decoder, err := NewDecoder(config) 99 | if err != nil { 100 | panic(err) 101 | } 102 | 103 | if err := decoder.Decode(input); err != nil { 104 | panic(err) 105 | } 106 | 107 | fmt.Printf("Unused keys: %#v", md.Unused) 108 | // Output: 109 | // Unused keys: []string{"email"} 110 | } 111 | 112 | func ExampleDecode_weaklyTypedInput() { 113 | type Person struct { 114 | Name string 115 | Age int 116 | Emails []string 117 | } 118 | 119 | // This input can come from anywhere, but typically comes from 120 | // something like decoding JSON, generated by a weakly typed language 121 | // such as PHP. 122 | input := map[string]interface{}{ 123 | "name": 123, // number => string 124 | "age": "42", // string => number 125 | "emails": map[string]interface{}{}, // empty map => empty array 126 | } 127 | 128 | var result Person 129 | config := &DecoderConfig{ 130 | WeaklyTypedInput: true, 131 | Result: &result, 132 | } 133 | 134 | decoder, err := NewDecoder(config) 135 | if err != nil { 136 | panic(err) 137 | } 138 | 139 | err = decoder.Decode(input) 140 | if err != nil { 141 | panic(err) 142 | } 143 | 144 | fmt.Printf("%#v", result) 145 | // Output: mapstructure.Person{Name:"123", Age:42, Emails:[]string{}} 146 | } 147 | 148 | func ExampleDecodePath() { 149 | var document string = `{ 150 | "userContext": { 151 | "conversationCredentials": { 152 | "sessionToken": "06142010_1:75bf6a413327dd71ebe8f3f30c5a4210a9b11e93c028d6e11abfca7ff" 153 | }, 154 | "valid": true, 155 | "isPasswordExpired": false, 156 | "cobrandId": 10000004, 157 | "channelId": -1, 158 | "locale": "en_US", 159 | "tncVersion": 2, 160 | "applicationId": "17CBE222A42161A3FF450E47CF4C1A00", 161 | "cobrandConversationCredentials": { 162 | "sessionToken": "06142010_1:b8d011fefbab8bf1753391b074ffedf9578612d676ed2b7f073b5785b" 163 | }, 164 | "preferenceInfo": { 165 | "currencyCode": "USD", 166 | "timeZone": "PST", 167 | "dateFormat": "MM/dd/yyyy", 168 | "currencyNotationType": { 169 | "currencyNotationType": "SYMBOL" 170 | }, 171 | "numberFormat": { 172 | "decimalSeparator": ".", 173 | "groupingSeparator": ",", 174 | "groupPattern": "###,##0.##" 175 | } 176 | } 177 | }, 178 | "lastLoginTime": 1375686841, 179 | "loginCount": 299, 180 | "passwordRecovered": false, 181 | "emailAddress": "johndoe@email.com", 182 | "loginName": "sptest1", 183 | "userId": 10483860, 184 | "userType": 185 | { 186 | "userTypeId": 1, 187 | "userTypeName": "normal_user" 188 | } 189 | }` 190 | 191 | type UserType struct { 192 | UserTypeId int 193 | UserTypeName string 194 | } 195 | 196 | type NumberFormat struct { 197 | DecimalSeparator string `jpath:"userContext.preferenceInfo.numberFormat.decimalSeparator"` 198 | GroupingSeparator string `jpath:"userContext.preferenceInfo.numberFormat.groupingSeparator"` 199 | GroupPattern string `jpath:"userContext.preferenceInfo.numberFormat.groupPattern"` 200 | } 201 | 202 | type User struct { 203 | Session string `jpath:"userContext.cobrandConversationCredentials.sessionToken"` 204 | CobrandId int `jpath:"userContext.cobrandId"` 205 | UserType UserType `jpath:"userType"` 206 | LoginName string `jpath:"loginName"` 207 | NumberFormat // This can also be a pointer to the struct (*NumberFormat) 208 | } 209 | 210 | docScript := []byte(document) 211 | var docMap map[string]interface{} 212 | json.Unmarshal(docScript, &docMap) 213 | 214 | var user User 215 | DecodePath(docMap, &user) 216 | 217 | fmt.Printf("%#v", user) 218 | // Output: 219 | // 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.##"}} 220 | } 221 | 222 | func ExampleDecodeSlicePath() { 223 | var document = `[{"name":"bill"},{"name":"lisa"}]` 224 | 225 | type NameDoc struct { 226 | Name string `jpath:"name"` 227 | } 228 | 229 | sliceScript := []byte(document) 230 | var sliceMap []map[string]interface{} 231 | json.Unmarshal(sliceScript, &sliceMap) 232 | 233 | var myslice []NameDoc 234 | DecodeSlicePath(sliceMap, &myslice) 235 | 236 | fmt.Printf("%#v", myslice) 237 | // Output: 238 | // []mapstructure.NameDoc{mapstructure.NameDoc{Name:"bill"}, mapstructure.NameDoc{Name:"lisa"}} 239 | } 240 | 241 | func ExampleDecodeWithEmbeddedSlice() { 242 | var document string = `{ 243 | "cobrandId": 10010352, 244 | "channelId": -1, 245 | "locale": "en_US", 246 | "tncVersion": 2, 247 | "categories":["rabbit","bunny","frog"], 248 | "people": [ 249 | { 250 | "name": "jack", 251 | "age": { 252 | "birth":10, 253 | "year":2000, 254 | "animals": [ 255 | { 256 | "barks":"yes", 257 | "tail":"yes" 258 | }, 259 | { 260 | "barks":"no", 261 | "tail":"yes" 262 | } 263 | ] 264 | } 265 | }, 266 | { 267 | "name": "jill", 268 | "age": { 269 | "birth":11, 270 | "year":2001 271 | } 272 | } 273 | ] 274 | }` 275 | 276 | type Animal struct { 277 | Barks string `jpath:"barks"` 278 | } 279 | 280 | type People struct { 281 | Age int `jpath:"age.birth"` // jpath is relative to the array 282 | Animals []Animal `jpath:"age.animals"` 283 | } 284 | 285 | type Items struct { 286 | Categories []string `jpath:"categories"` 287 | Peoples []People `jpath:"people"` // Specify the location of the array 288 | } 289 | 290 | docScript := []byte(document) 291 | var docMap map[string]interface{} 292 | json.Unmarshal(docScript, &docMap) 293 | 294 | var items Items 295 | DecodePath(docMap, &items) 296 | 297 | fmt.Printf("%#v", items) 298 | // Output: 299 | // 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)}}} 300 | } 301 | 302 | func ExampleDecodeWithAbstractField() { 303 | var document = `{"Error":[{"errorDetail":"Invalid Cobrand Credentials"}]}` 304 | 305 | type YodleeError struct { 306 | Error []map[string]interface{} `jpath:"Error"` 307 | } 308 | 309 | type CobrandContext struct { 310 | YodleeError 311 | } 312 | 313 | docScript := []byte(document) 314 | var docMap map[string]interface{} 315 | json.Unmarshal(docScript, &docMap) 316 | 317 | var cobrandContext CobrandContext 318 | DecodePath(docMap, &cobrandContext) 319 | 320 | fmt.Printf("%#v", cobrandContext) 321 | // Output: 322 | // mapstructure.CobrandContext{YodleeError:mapstructure.YodleeError{Error:[]map[string]interface {}{map[string]interface {}{"errorDetail":"Invalid Cobrand Credentials"}}}} 323 | } 324 | -------------------------------------------------------------------------------- /mapstructure_test.go: -------------------------------------------------------------------------------- 1 | package mapstructure 2 | 3 | import ( 4 | "encoding/json" 5 | "reflect" 6 | "sort" 7 | "testing" 8 | ) 9 | 10 | type Basic struct { 11 | Vstring string 12 | Vint int 13 | Vuint uint 14 | Vbool bool 15 | Vfloat float64 16 | Vextra string 17 | vsilent bool 18 | Vdata interface{} 19 | } 20 | 21 | type Embedded struct { 22 | Basic 23 | Vunique string 24 | } 25 | 26 | type EmbeddedPointer struct { 27 | *Basic 28 | Vunique string 29 | } 30 | 31 | type EmbeddedSquash struct { 32 | Basic `mapstructure:",squash"` 33 | Vunique string 34 | } 35 | 36 | type Map struct { 37 | Vfoo string 38 | Vother map[string]string 39 | } 40 | 41 | type MapOfStruct struct { 42 | Value map[string]Basic 43 | } 44 | 45 | type Nested struct { 46 | Vfoo string 47 | Vbar Basic 48 | } 49 | 50 | type Slice struct { 51 | Vfoo string 52 | Vbar []string 53 | } 54 | 55 | type SliceOfStruct struct { 56 | Value []Basic 57 | } 58 | 59 | type Tagged struct { 60 | Extra string `mapstructure:"bar,what,what"` 61 | Value string `mapstructure:"foo"` 62 | } 63 | 64 | type TypeConversionResult struct { 65 | IntToFloat float32 66 | IntToUint uint 67 | IntToBool bool 68 | IntToString string 69 | UintToInt int 70 | UintToFloat float32 71 | UintToBool bool 72 | UintToString string 73 | BoolToInt int 74 | BoolToUint uint 75 | BoolToFloat float32 76 | BoolToString string 77 | FloatToInt int 78 | FloatToUint uint 79 | FloatToBool bool 80 | FloatToString string 81 | StringToInt int 82 | StringToUint uint 83 | StringToBool bool 84 | StringToFloat float32 85 | SliceToMap map[string]interface{} 86 | MapToSlice []interface{} 87 | } 88 | 89 | func TestBasicTypes(t *testing.T) { 90 | t.Parallel() 91 | 92 | input := map[string]interface{}{ 93 | "vstring": "foo", 94 | "vint": 42, 95 | "Vuint": 42, 96 | "vbool": true, 97 | "Vfloat": 42.42, 98 | "vsilent": true, 99 | "vdata": 42, 100 | } 101 | 102 | var result Basic 103 | err := Decode(input, &result) 104 | if err != nil { 105 | t.Errorf("got an err: %s", err.Error()) 106 | t.FailNow() 107 | } 108 | 109 | if result.Vstring != "foo" { 110 | t.Errorf("vstring value should be 'foo': %#v", result.Vstring) 111 | } 112 | 113 | if result.Vint != 42 { 114 | t.Errorf("vint value should be 42: %#v", result.Vint) 115 | } 116 | 117 | if result.Vuint != 42 { 118 | t.Errorf("vuint value should be 42: %#v", result.Vuint) 119 | } 120 | 121 | if result.Vbool != true { 122 | t.Errorf("vbool value should be true: %#v", result.Vbool) 123 | } 124 | 125 | if result.Vfloat != 42.42 { 126 | t.Errorf("vfloat value should be 42.42: %#v", result.Vfloat) 127 | } 128 | 129 | if result.Vextra != "" { 130 | t.Errorf("vextra value should be empty: %#v", result.Vextra) 131 | } 132 | 133 | if result.vsilent != false { 134 | t.Error("vsilent should not be set, it is unexported") 135 | } 136 | 137 | if result.Vdata != 42 { 138 | t.Error("vdata should be valid") 139 | } 140 | } 141 | 142 | func TestBasic_IntWithFloat(t *testing.T) { 143 | t.Parallel() 144 | 145 | input := map[string]interface{}{ 146 | "vint": float64(42), 147 | } 148 | 149 | var result Basic 150 | err := Decode(input, &result) 151 | if err != nil { 152 | t.Fatalf("got an err: %s", err) 153 | } 154 | } 155 | 156 | func TestDecode_Embedded(t *testing.T) { 157 | t.Parallel() 158 | 159 | input := map[string]interface{}{ 160 | "vstring": "foo", 161 | "Basic": map[string]interface{}{ 162 | "vstring": "innerfoo", 163 | }, 164 | "vunique": "bar", 165 | } 166 | 167 | var result Embedded 168 | err := Decode(input, &result) 169 | if err != nil { 170 | t.Fatalf("got an err: %s", err.Error()) 171 | } 172 | 173 | if result.Vstring != "innerfoo" { 174 | t.Errorf("vstring value should be 'innerfoo': %#v", result.Vstring) 175 | } 176 | 177 | if result.Vunique != "bar" { 178 | t.Errorf("vunique value should be 'bar': %#v", result.Vunique) 179 | } 180 | } 181 | 182 | func TestDecode_EmbeddedPointer(t *testing.T) { 183 | t.Parallel() 184 | 185 | input := map[string]interface{}{ 186 | "vstring": "foo", 187 | "Basic": map[string]interface{}{ 188 | "vstring": "innerfoo", 189 | }, 190 | "vunique": "bar", 191 | } 192 | 193 | var result EmbeddedPointer 194 | err := Decode(input, &result) 195 | if err == nil { 196 | t.Fatal("should get error") 197 | } 198 | } 199 | 200 | func TestDecode_EmbeddedSquash(t *testing.T) { 201 | t.Parallel() 202 | 203 | input := map[string]interface{}{ 204 | "vstring": "foo", 205 | "vunique": "bar", 206 | } 207 | 208 | var result EmbeddedSquash 209 | err := Decode(input, &result) 210 | if err != nil { 211 | t.Fatalf("got an err: %s", err.Error()) 212 | } 213 | 214 | if result.Vstring != "foo" { 215 | t.Errorf("vstring value should be 'foo': %#v", result.Vstring) 216 | } 217 | 218 | if result.Vunique != "bar" { 219 | t.Errorf("vunique value should be 'bar': %#v", result.Vunique) 220 | } 221 | } 222 | 223 | func TestDecode_DecodeHook(t *testing.T) { 224 | t.Parallel() 225 | 226 | input := map[string]interface{}{ 227 | "vint": "WHAT", 228 | } 229 | 230 | decodeHook := func(from reflect.Kind, to reflect.Kind, v interface{}) (interface{}, error) { 231 | if from == reflect.String && to != reflect.String { 232 | return 5, nil 233 | } 234 | 235 | return v, nil 236 | } 237 | 238 | var result Basic 239 | config := &DecoderConfig{ 240 | DecodeHook: decodeHook, 241 | Result: &result, 242 | } 243 | 244 | decoder, err := NewDecoder(config) 245 | if err != nil { 246 | t.Fatalf("err: %s", err) 247 | } 248 | 249 | err = decoder.Decode(input) 250 | if err != nil { 251 | t.Fatalf("got an err: %s", err) 252 | } 253 | 254 | if result.Vint != 5 { 255 | t.Errorf("vint should be 5: %#v", result.Vint) 256 | } 257 | } 258 | 259 | func TestDecode_Nil(t *testing.T) { 260 | t.Parallel() 261 | 262 | var input interface{} = nil 263 | result := Basic{ 264 | Vstring: "foo", 265 | } 266 | 267 | err := Decode(input, &result) 268 | if err != nil { 269 | t.Fatalf("err: %s", err) 270 | } 271 | 272 | if result.Vstring != "foo" { 273 | t.Fatalf("bad: %#v", result.Vstring) 274 | } 275 | } 276 | 277 | func TestDecode_NonStruct(t *testing.T) { 278 | t.Parallel() 279 | 280 | input := map[string]interface{}{ 281 | "foo": "bar", 282 | "bar": "baz", 283 | } 284 | 285 | var result map[string]string 286 | err := Decode(input, &result) 287 | if err != nil { 288 | t.Fatalf("err: %s", err) 289 | } 290 | 291 | if result["foo"] != "bar" { 292 | t.Fatal("foo is not bar") 293 | } 294 | } 295 | 296 | func TestDecode_TypeConversion(t *testing.T) { 297 | input := map[string]interface{}{ 298 | "IntToFloat": 42, 299 | "IntToUint": 42, 300 | "IntToBool": 1, 301 | "IntToString": 42, 302 | "UintToInt": 42, 303 | "UintToFloat": 42, 304 | "UintToBool": 42, 305 | "UintToString": 42, 306 | "BoolToInt": true, 307 | "BoolToUint": true, 308 | "BoolToFloat": true, 309 | "BoolToString": true, 310 | "FloatToInt": 42.42, 311 | "FloatToUint": 42.42, 312 | "FloatToBool": 42.42, 313 | "FloatToString": 42.42, 314 | "StringToInt": "42", 315 | "StringToUint": "42", 316 | "StringToBool": "1", 317 | "StringToFloat": "42.42", 318 | "SliceToMap": []interface{}{}, 319 | "MapToSlice": map[string]interface{}{}, 320 | } 321 | 322 | expectedResultStrict := TypeConversionResult{ 323 | IntToFloat: 42.0, 324 | IntToUint: 42, 325 | UintToInt: 42, 326 | UintToFloat: 42, 327 | BoolToInt: 0, 328 | BoolToUint: 0, 329 | BoolToFloat: 0, 330 | FloatToInt: 42, 331 | FloatToUint: 42, 332 | } 333 | 334 | expectedResultWeak := TypeConversionResult{ 335 | IntToFloat: 42.0, 336 | IntToUint: 42, 337 | IntToBool: true, 338 | IntToString: "42", 339 | UintToInt: 42, 340 | UintToFloat: 42, 341 | UintToBool: true, 342 | UintToString: "42", 343 | BoolToInt: 1, 344 | BoolToUint: 1, 345 | BoolToFloat: 1, 346 | BoolToString: "1", 347 | FloatToInt: 42, 348 | FloatToUint: 42, 349 | FloatToBool: true, 350 | FloatToString: "42.42", 351 | StringToInt: 42, 352 | StringToUint: 42, 353 | StringToBool: true, 354 | StringToFloat: 42.42, 355 | SliceToMap: map[string]interface{}{}, 356 | MapToSlice: []interface{}{}, 357 | } 358 | 359 | // Test strict type conversion 360 | var resultStrict TypeConversionResult 361 | err := Decode(input, &resultStrict) 362 | if err == nil { 363 | t.Errorf("should return an error") 364 | } 365 | if !reflect.DeepEqual(resultStrict, expectedResultStrict) { 366 | t.Errorf("expected %v, got: %v", expectedResultStrict, resultStrict) 367 | } 368 | 369 | // Test weak type conversion 370 | var decoder *Decoder 371 | var resultWeak TypeConversionResult 372 | 373 | config := &DecoderConfig{ 374 | WeaklyTypedInput: true, 375 | Result: &resultWeak, 376 | } 377 | 378 | decoder, err = NewDecoder(config) 379 | if err != nil { 380 | t.Fatalf("err: %s", err) 381 | } 382 | 383 | err = decoder.Decode(input) 384 | if err != nil { 385 | t.Fatalf("got an err: %s", err) 386 | } 387 | 388 | if !reflect.DeepEqual(resultWeak, expectedResultWeak) { 389 | t.Errorf("expected \n%#v, got: \n%#v", expectedResultWeak, resultWeak) 390 | } 391 | } 392 | 393 | func TestDecoder_ErrorUnused(t *testing.T) { 394 | t.Parallel() 395 | 396 | input := map[string]interface{}{ 397 | "vstring": "hello", 398 | "foo": "bar", 399 | } 400 | 401 | var result Basic 402 | config := &DecoderConfig{ 403 | ErrorUnused: true, 404 | Result: &result, 405 | } 406 | 407 | decoder, err := NewDecoder(config) 408 | if err != nil { 409 | t.Fatalf("err: %s", err) 410 | } 411 | 412 | err = decoder.Decode(input) 413 | if err == nil { 414 | t.Fatal("expected error") 415 | } 416 | } 417 | 418 | func TestMap(t *testing.T) { 419 | t.Parallel() 420 | 421 | input := map[string]interface{}{ 422 | "vfoo": "foo", 423 | "vother": map[interface{}]interface{}{ 424 | "foo": "foo", 425 | "bar": "bar", 426 | }, 427 | } 428 | 429 | var result Map 430 | err := Decode(input, &result) 431 | if err != nil { 432 | t.Fatalf("got an error: %s", err) 433 | } 434 | 435 | if result.Vfoo != "foo" { 436 | t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) 437 | } 438 | 439 | if result.Vother == nil { 440 | t.Fatal("vother should not be nil") 441 | } 442 | 443 | if len(result.Vother) != 2 { 444 | t.Error("vother should have two items") 445 | } 446 | 447 | if result.Vother["foo"] != "foo" { 448 | t.Errorf("'foo' key should be foo, got: %#v", result.Vother["foo"]) 449 | } 450 | 451 | if result.Vother["bar"] != "bar" { 452 | t.Errorf("'bar' key should be bar, got: %#v", result.Vother["bar"]) 453 | } 454 | } 455 | 456 | func TestMapOfStruct(t *testing.T) { 457 | t.Parallel() 458 | 459 | input := map[string]interface{}{ 460 | "value": map[string]interface{}{ 461 | "foo": map[string]string{"vstring": "one"}, 462 | "bar": map[string]string{"vstring": "two"}, 463 | }, 464 | } 465 | 466 | var result MapOfStruct 467 | err := Decode(input, &result) 468 | if err != nil { 469 | t.Fatalf("got an err: %s", err) 470 | } 471 | 472 | if result.Value == nil { 473 | t.Fatal("value should not be nil") 474 | } 475 | 476 | if len(result.Value) != 2 { 477 | t.Error("value should have two items") 478 | } 479 | 480 | if result.Value["foo"].Vstring != "one" { 481 | t.Errorf("foo value should be 'one', got: %s", result.Value["foo"].Vstring) 482 | } 483 | 484 | if result.Value["bar"].Vstring != "two" { 485 | t.Errorf("bar value should be 'two', got: %s", result.Value["bar"].Vstring) 486 | } 487 | } 488 | 489 | func TestNestedType(t *testing.T) { 490 | t.Parallel() 491 | 492 | input := map[string]interface{}{ 493 | "vfoo": "foo", 494 | "vbar": map[string]interface{}{ 495 | "vstring": "foo", 496 | "vint": 42, 497 | "vbool": true, 498 | }, 499 | } 500 | 501 | var result Nested 502 | err := Decode(input, &result) 503 | if err != nil { 504 | t.Fatalf("got an err: %s", err.Error()) 505 | } 506 | 507 | if result.Vfoo != "foo" { 508 | t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) 509 | } 510 | 511 | if result.Vbar.Vstring != "foo" { 512 | t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring) 513 | } 514 | 515 | if result.Vbar.Vint != 42 { 516 | t.Errorf("vint value should be 42: %#v", result.Vbar.Vint) 517 | } 518 | 519 | if result.Vbar.Vbool != true { 520 | t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool) 521 | } 522 | 523 | if result.Vbar.Vextra != "" { 524 | t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra) 525 | } 526 | } 527 | 528 | func TestNestedTypePointer(t *testing.T) { 529 | t.Parallel() 530 | 531 | input := map[string]interface{}{ 532 | "vfoo": "foo", 533 | "vbar": &map[string]interface{}{ 534 | "vstring": "foo", 535 | "vint": 42, 536 | "vbool": true, 537 | }, 538 | } 539 | 540 | var result Nested 541 | err := Decode(input, &result) 542 | if err != nil { 543 | t.Fatalf("got an err: %s", err.Error()) 544 | } 545 | 546 | if result.Vfoo != "foo" { 547 | t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) 548 | } 549 | 550 | if result.Vbar.Vstring != "foo" { 551 | t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring) 552 | } 553 | 554 | if result.Vbar.Vint != 42 { 555 | t.Errorf("vint value should be 42: %#v", result.Vbar.Vint) 556 | } 557 | 558 | if result.Vbar.Vbool != true { 559 | t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool) 560 | } 561 | 562 | if result.Vbar.Vextra != "" { 563 | t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra) 564 | } 565 | } 566 | 567 | func TestSlice(t *testing.T) { 568 | t.Parallel() 569 | 570 | inputStringSlice := map[string]interface{}{ 571 | "vfoo": "foo", 572 | "vbar": []string{"foo", "bar", "baz"}, 573 | } 574 | 575 | inputStringSlicePointer := map[string]interface{}{ 576 | "vfoo": "foo", 577 | "vbar": &[]string{"foo", "bar", "baz"}, 578 | } 579 | 580 | outputStringSlice := &Slice{ 581 | "foo", 582 | []string{"foo", "bar", "baz"}, 583 | } 584 | 585 | testSliceInput(t, inputStringSlice, outputStringSlice) 586 | testSliceInput(t, inputStringSlicePointer, outputStringSlice) 587 | } 588 | 589 | func TestSliceOfStruct(t *testing.T) { 590 | t.Parallel() 591 | 592 | input := map[string]interface{}{ 593 | "value": []map[string]interface{}{ 594 | {"vstring": "one"}, 595 | {"vstring": "two"}, 596 | }, 597 | } 598 | 599 | var result SliceOfStruct 600 | err := Decode(input, &result) 601 | if err != nil { 602 | t.Fatalf("got unexpected error: %s", err) 603 | } 604 | 605 | if len(result.Value) != 2 { 606 | t.Fatalf("expected two values, got %d", len(result.Value)) 607 | } 608 | 609 | if result.Value[0].Vstring != "one" { 610 | t.Errorf("first value should be 'one', got: %s", result.Value[0].Vstring) 611 | } 612 | 613 | if result.Value[1].Vstring != "two" { 614 | t.Errorf("second value should be 'two', got: %s", result.Value[1].Vstring) 615 | } 616 | } 617 | 618 | func TestInvalidType(t *testing.T) { 619 | t.Parallel() 620 | 621 | input := map[string]interface{}{ 622 | "vstring": 42, 623 | } 624 | 625 | var result Basic 626 | err := Decode(input, &result) 627 | if err == nil { 628 | t.Fatal("error should exist") 629 | } 630 | 631 | derr, ok := err.(*Error) 632 | if !ok { 633 | t.Fatalf("error should be kind of Error, instead: %#v", err) 634 | } 635 | 636 | if derr.Errors[0] != "'Vstring' expected type 'string', got unconvertible type 'int'" { 637 | t.Errorf("got unexpected error: %s", err) 638 | } 639 | } 640 | 641 | func TestMetadata(t *testing.T) { 642 | t.Parallel() 643 | 644 | input := map[string]interface{}{ 645 | "vfoo": "foo", 646 | "vbar": map[string]interface{}{ 647 | "vstring": "foo", 648 | "Vuint": 42, 649 | "foo": "bar", 650 | }, 651 | "bar": "nil", 652 | } 653 | 654 | var md Metadata 655 | var result Nested 656 | config := &DecoderConfig{ 657 | Metadata: &md, 658 | Result: &result, 659 | } 660 | 661 | decoder, err := NewDecoder(config) 662 | if err != nil { 663 | t.Fatalf("err: %s", err) 664 | } 665 | 666 | err = decoder.Decode(input) 667 | if err != nil { 668 | t.Fatalf("err: %s", err.Error()) 669 | } 670 | 671 | expectedKeys := []string{"Vfoo", "Vbar.Vstring", "Vbar.Vuint", "Vbar"} 672 | if !reflect.DeepEqual(md.Keys, expectedKeys) { 673 | t.Fatalf("bad keys: %#v", md.Keys) 674 | } 675 | 676 | expectedUnused := []string{"Vbar.foo", "bar"} 677 | if !reflect.DeepEqual(md.Unused, expectedUnused) { 678 | t.Fatalf("bad unused: %#v", md.Unused) 679 | } 680 | } 681 | 682 | func TestMetadata_Embedded(t *testing.T) { 683 | t.Parallel() 684 | 685 | input := map[string]interface{}{ 686 | "vstring": "foo", 687 | "vunique": "bar", 688 | } 689 | 690 | var md Metadata 691 | var result EmbeddedSquash 692 | config := &DecoderConfig{ 693 | Metadata: &md, 694 | Result: &result, 695 | } 696 | 697 | decoder, err := NewDecoder(config) 698 | if err != nil { 699 | t.Fatalf("err: %s", err) 700 | } 701 | 702 | err = decoder.Decode(input) 703 | if err != nil { 704 | t.Fatalf("err: %s", err.Error()) 705 | } 706 | 707 | expectedKeys := []string{"Vstring", "Vunique"} 708 | 709 | sort.Strings(md.Keys) 710 | if !reflect.DeepEqual(md.Keys, expectedKeys) { 711 | t.Fatalf("bad keys: %#v", md.Keys) 712 | } 713 | 714 | expectedUnused := []string{} 715 | if !reflect.DeepEqual(md.Unused, expectedUnused) { 716 | t.Fatalf("bad unused: %#v", md.Unused) 717 | } 718 | } 719 | 720 | func TestNonPtrValue(t *testing.T) { 721 | t.Parallel() 722 | 723 | err := Decode(map[string]interface{}{}, Basic{}) 724 | if err == nil { 725 | t.Fatal("error should exist") 726 | } 727 | 728 | if err.Error() != "result must be a pointer" { 729 | t.Errorf("got unexpected error: %s", err) 730 | } 731 | } 732 | 733 | func TestTagged(t *testing.T) { 734 | t.Parallel() 735 | 736 | input := map[string]interface{}{ 737 | "foo": "bar", 738 | "bar": "value", 739 | } 740 | 741 | var result Tagged 742 | err := Decode(input, &result) 743 | if err != nil { 744 | t.Fatalf("unexpected error: %s", err) 745 | } 746 | 747 | if result.Value != "bar" { 748 | t.Errorf("value should be 'bar', got: %#v", result.Value) 749 | } 750 | 751 | if result.Extra != "value" { 752 | t.Errorf("extra should be 'value', got: %#v", result.Extra) 753 | } 754 | } 755 | 756 | func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) { 757 | var result Slice 758 | err := Decode(input, &result) 759 | if err != nil { 760 | t.Fatalf("got error: %s", err) 761 | } 762 | 763 | if result.Vfoo != expected.Vfoo { 764 | t.Errorf("Vfoo expected '%s', got '%s'", expected.Vfoo, result.Vfoo) 765 | } 766 | 767 | if result.Vbar == nil { 768 | t.Fatalf("Vbar a slice, got '%#v'", result.Vbar) 769 | } 770 | 771 | if len(result.Vbar) != len(expected.Vbar) { 772 | t.Errorf("Vbar length should be %d, got %d", len(expected.Vbar), len(result.Vbar)) 773 | } 774 | 775 | for i, v := range result.Vbar { 776 | if v != expected.Vbar[i] { 777 | t.Errorf( 778 | "Vbar[%d] should be '%#v', got '%#v'", 779 | i, expected.Vbar[i], v) 780 | } 781 | } 782 | } 783 | 784 | func TestDecodePath(t *testing.T) { 785 | var document string = `{ 786 | "userContext": { 787 | "cobrandId": 10000004, 788 | "channelId": -1, 789 | "locale": "en_US", 790 | "tncVersion": 2, 791 | "applicationId": "17CBE222A42161A3FF450E47CF4C1A00", 792 | "cobrandConversationCredentials": { 793 | "sessionToken": "06142010_1:b8d011fefbab8bf1753391b074ffedf9578612d676ed2b7f073b5785b" 794 | }, 795 | "preferenceInfo": { 796 | "currencyCode": "USD", 797 | "timeZone": "PST", 798 | "dateFormat": "MM/dd/yyyy", 799 | "currencyNotationType": { 800 | "currencyNotationType": "SYMBOL" 801 | }, 802 | "numberFormat": { 803 | "decimalSeparator": ".", 804 | "groupingSeparator": ",", 805 | "groupPattern": "###,##0.##" 806 | } 807 | } 808 | }, 809 | "loginName": "sptest1", 810 | "userId": 10483860, 811 | "userType": 812 | { 813 | "userTypeId": 1, 814 | "userTypeName": "normal_user" 815 | } 816 | }` 817 | 818 | type UserType struct { 819 | UserTypeId int 820 | UserTypeName string 821 | } 822 | 823 | type NumberFormat struct { 824 | DecimalSeparator string `jpath:"userContext.preferenceInfo.numberFormat.decimalSeparator"` 825 | GroupingSeparator string `jpath:"userContext.preferenceInfo.numberFormat.groupingSeparator"` 826 | GroupPattern string `jpath:"userContext.preferenceInfo.numberFormat.groupPattern"` 827 | } 828 | 829 | type User struct { 830 | Session string `jpath:"userContext.cobrandConversationCredentials.sessionToken"` 831 | CobrandId int `jpath:"userContext.cobrandId"` 832 | UserType UserType `jpath:"userType"` 833 | LoginName string `jpath:"loginName"` 834 | *NumberFormat 835 | } 836 | 837 | docScript := []byte(document) 838 | var docMap map[string]interface{} 839 | err := json.Unmarshal(docScript, &docMap) 840 | if err != nil { 841 | t.Fatalf("Unable To Unmarshal Test Document, %s", err) 842 | } 843 | 844 | var user User 845 | DecodePath(docMap, &user) 846 | 847 | session := "06142010_1:b8d011fefbab8bf1753391b074ffedf9578612d676ed2b7f073b5785b" 848 | if user.Session != session { 849 | t.Errorf("user.Session should be '%s', we got '%s'", session, user.Session) 850 | } 851 | 852 | cobrandId := 10000004 853 | if user.CobrandId != cobrandId { 854 | t.Errorf("user.CobrandId should be '%d', we got '%d'", cobrandId, user.CobrandId) 855 | } 856 | 857 | loginName := "sptest1" 858 | if user.LoginName != loginName { 859 | t.Errorf("user.LoginName should be '%s', we got '%s'", loginName, user.LoginName) 860 | } 861 | 862 | userTypeId := 1 863 | if user.UserType.UserTypeId != userTypeId { 864 | t.Errorf("user.UserType.UserTypeId should be '%d', we got '%d'", userTypeId, user.UserType.UserTypeId) 865 | } 866 | 867 | userTypeName := "normal_user" 868 | if user.UserType.UserTypeName != userTypeName { 869 | t.Errorf("user.UserType.UserTypeName should be '%s', we got '%s'", userTypeName, user.UserType.UserTypeName) 870 | } 871 | 872 | decimalSeparator := "." 873 | if user.NumberFormat.DecimalSeparator != decimalSeparator { 874 | t.Errorf("user.NumberFormat.DecimalSeparator should be '%s', we got '%s'", decimalSeparator, user.NumberFormat.DecimalSeparator) 875 | } 876 | 877 | groupingSeparator := "," 878 | if user.NumberFormat.GroupingSeparator != groupingSeparator { 879 | t.Errorf("user.NumberFormat.GroupingSeparator should be '%s', we got '%s'", groupingSeparator, user.NumberFormat.GroupingSeparator) 880 | } 881 | 882 | groupPattern := "###,##0.##" 883 | if user.NumberFormat.GroupPattern != groupPattern { 884 | t.Errorf("user.NumberFormat.GroupPattern should be '%s', we got '%s'", groupPattern, user.NumberFormat.GroupPattern) 885 | } 886 | } 887 | 888 | func TestDecodeSlicePath(t *testing.T) { 889 | var document = `[{"name":"bill"},{"name":"lisa"}]` 890 | 891 | type NameDoc struct { 892 | Name string `jpath:"name"` 893 | } 894 | 895 | sliceScript := []byte(document) 896 | var sliceMap []map[string]interface{} 897 | json.Unmarshal(sliceScript, &sliceMap) 898 | 899 | var myslice1 []NameDoc 900 | err1 := DecodeSlicePath(sliceMap, &myslice1) 901 | 902 | var myslice2 []*NameDoc 903 | err2 := DecodeSlicePath(sliceMap, &myslice2) 904 | 905 | name1 := "bill" 906 | name2 := "lisa" 907 | 908 | if err1 != nil { 909 | t.Fatal(err1) 910 | } 911 | 912 | if err2 != nil { 913 | t.Fatal(err1) 914 | } 915 | 916 | if myslice1[0].Name != name1 { 917 | t.Errorf("myslice1[0].Name should be '%s', we got '%s'", name1, myslice1[0].Name) 918 | } 919 | 920 | if myslice1[1].Name != name2 { 921 | t.Errorf("myslice1[1].Name should be '%s', we got '%s'", name1, myslice1[1].Name) 922 | } 923 | 924 | if myslice2[0].Name != name1 { 925 | t.Errorf("myslice2[0].Name should be '%s', we got '%s'", name1, myslice1[0].Name) 926 | } 927 | 928 | if myslice2[1].Name != name2 { 929 | t.Errorf("myslice1[1].Name should be '%s', we got '%s'", name2, myslice2[1].Name) 930 | } 931 | } 932 | 933 | func TestDecodeWithEmbeddedSlice(t *testing.T) { 934 | var document string = `{ 935 | "cobrandId": 10010352, 936 | "channelId": -1, 937 | "locale": "en_US", 938 | "tncVersion": 2, 939 | "categories":["rabbit","bunny","frog"], 940 | "people": [ 941 | { 942 | "name": "jack", 943 | "age": { 944 | "birth":10, 945 | "year":2000, 946 | "animals": [ 947 | { 948 | "barks":"yes", 949 | "tail":"yes" 950 | }, 951 | { 952 | "barks":"no", 953 | "tail":"yes" 954 | } 955 | ] 956 | } 957 | }, 958 | { 959 | "name": "jill", 960 | "age": { 961 | "birth":11, 962 | "year":2001 963 | } 964 | } 965 | ] 966 | }` 967 | 968 | type Animal struct { 969 | Barks string `jpath:"barks"` 970 | } 971 | 972 | type People struct { 973 | Age int `jpath:"age.birth"` 974 | Animals []Animal `jpath:"age.animals"` 975 | } 976 | 977 | type Items struct { 978 | Categories []string `jpath:"categories"` 979 | Peoples []People `jpath:"people"` 980 | } 981 | 982 | docScript := []byte(document) 983 | var docMap map[string]interface{} 984 | json.Unmarshal(docScript, &docMap) 985 | 986 | items := Items{} 987 | DecodePath(docMap, &items) 988 | 989 | if len(items.Categories) != 3 { 990 | t.Error("items.Categories did not decode") 991 | return 992 | } 993 | 994 | if len(items.Peoples) != 2 { 995 | t.Error("items.Peoples did not decode") 996 | return 997 | } 998 | 999 | if len(items.Peoples[0].Animals) != 2 { 1000 | t.Error("items.Peoples[0].Animals did not decode") 1001 | return 1002 | } 1003 | 1004 | age := 10 1005 | if items.Peoples[0].Age != 10 { 1006 | t.Errorf("items.Peoples[0].Age should be '%d', we got '%s'", age, items.Peoples[0].Age) 1007 | } 1008 | 1009 | barks := "yes" 1010 | if items.Peoples[0].Animals[0].Barks != barks { 1011 | t.Errorf("items.Peoples[0].Animals[0].Barks should be '%d', we got '%s'", barks, items.Peoples[0].Animals[0].Barks) 1012 | } 1013 | } 1014 | 1015 | func TestDecodeWithAbstractField(t *testing.T) { 1016 | var document = `{"Error":[{"errorDetail":"Invalid Cobrand Credentials"}]}` 1017 | 1018 | type AnError struct { 1019 | Error []map[string]interface{} `jpath:"Error"` 1020 | } 1021 | 1022 | type Context struct { 1023 | *AnError 1024 | } 1025 | 1026 | docScript := []byte(document) 1027 | var docMap map[string]interface{} 1028 | json.Unmarshal(docScript, &docMap) 1029 | 1030 | context := Context{} 1031 | DecodePath(docMap, &context) 1032 | 1033 | errorDetail := "Invalid Cobrand Credentials" 1034 | if context.Error[0]["errorDetail"].(string) != errorDetail { 1035 | t.Errorf("context.Error[0][\"errorDetail\"] should be '%s', we got '%s'", errorDetail, context.Error[0]["errorDetail"].(string)) 1036 | } 1037 | } 1038 | 1039 | func TestDecodePointerToPointer(t *testing.T) { 1040 | var document = `{"Error":[{"errorDetail":"Invalid Cobrand Credentials"}]}` 1041 | 1042 | type AnError struct { 1043 | Error []map[string]interface{} `jpath:"Error"` 1044 | } 1045 | 1046 | type APointerError struct { 1047 | *AnError 1048 | } 1049 | 1050 | type Context struct { 1051 | *APointerError 1052 | } 1053 | 1054 | docScript := []byte(document) 1055 | var docMap map[string]interface{} 1056 | json.Unmarshal(docScript, &docMap) 1057 | 1058 | var context Context 1059 | DecodePath(docMap, &context) 1060 | 1061 | errorDetail := "Invalid Cobrand Credentials" 1062 | if context.Error != nil { 1063 | if context.Error[0]["errorDetail"].(string) != errorDetail { 1064 | t.Errorf("context.Error[0][\"errorDetail\"] should be '%s', we got '%s'", errorDetail, context.Error[0]["errorDetail"].(string)) 1065 | } 1066 | } 1067 | } 1068 | --------------------------------------------------------------------------------