package mapstructure

import "k8s.io/kubernetes/Godeps/_workspace/src/github.com/mitchellh/mapstructure"

The mapstructure package exposes functionality to convert an abitrary map[string]interface{} into a native Go structure.

The Go structure can be arbitrarily complex, containing slices, other structs, etc. and the decoder will properly decode nested maps and so on into the proper structures in the native Go struct. See the examples to see what the decoder is capable of.

Index

Examples

Functions

func Decode

func Decode(m interface{}, rawVal interface{}) error

Decode takes a map and uses reflection to convert it into the given Go native structure. val must be a pointer to a struct.

Example

Code:

{
	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"}}
}

Output:

mapstructure.Person{Name:"Mitchell", Age:91, Emails:[]string{"one", "two", "three"}, Extra:map[string]string{"twitter":"mitchellh"}}
Example (Errors)

Code:

{
	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'
}

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'
Example (Metadata)

Code:

{
	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"}
}

Output:

Unused keys: []string{"email"}
Example (Tags)

Code:

{
	// Note that the mapstructure tags defined in the struct type
	// can indicate which fields the values are mapped to.
	type Person struct {
		Name string `mapstructure:"person_name"`
		Age  int    `mapstructure:"person_age"`
	}

	input := map[string]interface{}{
		"person_name": "Mitchell",
		"person_age":  91,
	}

	var result Person
	err := Decode(input, &result)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%#v", result)
	// Output:
	// mapstructure.Person{Name:"Mitchell", Age:91}
}

Output:

mapstructure.Person{Name:"Mitchell", Age:91}
Example (WeaklyTypedInput)

Code:

{
	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{}}
}

Output:

mapstructure.Person{Name:"123", Age:42, Emails:[]string{}}

func WeakDecode

func WeakDecode(input, output interface{}) error

WeakDecode is the same as Decode but is shorthand to enable WeaklyTypedInput. See DecoderConfig for more info.

func WeaklyTypedHook

func WeaklyTypedHook(
	f reflect.Kind,
	t reflect.Kind,
	data interface{}) (interface{}, error)

Types

type DecodeHookFunc

type DecodeHookFunc func(
	from reflect.Kind,
	to reflect.Kind,
	data interface{}) (interface{}, error)

DecodeHookFunc is the callback function that can be used for data transformations. See "DecodeHook" in the DecoderConfig struct.

func ComposeDecodeHookFunc

func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc

ComposeDecodeHookFunc creates a single DecodeHookFunc that automatically composes multiple DecodeHookFuncs.

The composed funcs are called in order, with the result of the previous transformation.

func StringToSliceHookFunc

func StringToSliceHookFunc(sep string) DecodeHookFunc

StringToSliceHookFunc returns a DecodeHookFunc that converts string to []string by splitting on the given sep.

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

A Decoder takes a raw interface value and turns it into structured data, keeping track of rich error information along the way in case anything goes wrong. Unlike the basic top-level Decode method, you can more finely control how the Decoder behaves using the DecoderConfig structure. The top-level Decode method is just a convenience that sets up the most basic Decoder.

func NewDecoder

func NewDecoder(config *DecoderConfig) (*Decoder, error)

NewDecoder returns a new decoder for the given configuration. Once a decoder has been returned, the same configuration must not be used again.

func (*Decoder) Decode

func (d *Decoder) Decode(raw interface{}) error

Decode decodes the given raw interface to the target pointer specified by the configuration.

type DecoderConfig

type DecoderConfig struct {
	// DecodeHook, if set, will be called before any decoding and any
	// type conversion (if WeaklyTypedInput is on). This lets you modify
	// the values before they're set down onto the resulting struct.
	//
	// If an error is returned, the entire decode will fail with that
	// error.
	DecodeHook DecodeHookFunc

	// If ErrorUnused is true, then it is an error for there to exist
	// keys in the original map that were unused in the decoding process
	// (extra keys).
	ErrorUnused bool

	// If WeaklyTypedInput is true, the decoder will make the following
	// "weak" conversions:
	//
	//   - bools to string (true = "1", false = "0")
	//   - numbers to string (base 10)
	//   - bools to int/uint (true = 1, false = 0)
	//   - strings to int/uint (base implied by prefix)
	//   - int to bool (true if value != 0)
	//   - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F,
	//     FALSE, false, False. Anything else is an error)
	//   - empty array = empty map and vice versa
	//
	WeaklyTypedInput bool

	// Metadata is the struct that will contain extra metadata about
	// the decoding. If this is nil, then no metadata will be tracked.
	Metadata *Metadata

	// Result is a pointer to the struct that will contain the decoded
	// value.
	Result interface{}

	// The tag name that mapstructure reads for field names. This
	// defaults to "mapstructure"
	TagName string
}

DecoderConfig is the configuration that is used to create a new decoder and allows customization of various aspects of decoding.

type Error

type Error struct {
	Errors []string
}

Error implements the error interface and can represents multiple errors that occur in the course of a single decode.

func (*Error) Error

func (e *Error) Error() string

type Metadata

type Metadata struct {
	// Keys are the keys of the structure which were successfully decoded
	Keys []string

	// Unused is a slice of keys that were found in the raw value but
	// weren't decoded since there was no matching field in the result interface
	Unused []string
}

Metadata contains information about decoding a structure that is tedious or difficult to get otherwise.

Source Files

decode_hooks.go error.go mapstructure.go

Version
v0.14.2
Published
Apr 8, 2015
Platform
windows/amd64
Imports
6 packages
Last checked
4 minutes ago

Tools for package owners.