]>
Commit | Line | Data |
---|---|---|
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/mitchellh/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` function has 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. |