commit | 5e6ae737dfb5b93d84417eff5f15143ef36ad23f | [log] [tgz] |
---|---|---|
author | Mitchell Hashimoto <mitchell.hashimoto@gmail.com> | Sun May 19 22:31:34 2013 -0700 |
committer | Mitchell Hashimoto <mitchell.hashimoto@gmail.com> | Sun May 19 22:31:34 2013 -0700 |
tree | 48abcb0f5102069b6828a9c164ce8634b1da91be | |
parent | c44d22219d74842a90a94fe833001829e5af3a00 [diff] |
Fix README example
mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling.
This library is most useful when decoding values from some data stream (JSON, Gob, etc.) where you don't quite know the structure of the underlying data until you read a part of it. You can therefore read a map[string]interface{}
and use this library to decode it into the proper underlying native Go structure.
Standard go get
:
$ go get github.com/mitchellh/mapstructure
import ( "fmt" "github.com/mitchellh/mapstructure" ) 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 := mapstructure.Decode(input, &result) if err != nil { panic(err) } // The value of "result" now contains what you would expect. The decoding // process is properly type-checked and human-friendly errors are returned, // if any. fmt.Printf("%#v", result)
If decoding fails for any reason, very helpful errors are returned. For example, the string format of a mapstructure.Error
may look like this:
5 error(s) decoding: * 'Name' expected type 'string', got 'int' * 'Age' expected type 'int', got 'string' * 'Emails[0]' expected type 'string', got 'int' * 'Emails[1]' expected type 'string', got 'int' * 'Emails[2]' expected type 'string', got 'int'