mapstructure
Go library for decoding generic map values into native Go structures and vice versa.
Top Related Projects
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
Utilities for Go structs
safe and easy casting from one type to another in Go
Quick Overview
The mitchellh/mapstructure
library is a Go package that provides a way to decode generic map values into native Go structures. It is a powerful and flexible tool for working with dynamic data structures in Go applications.
Pros
- Flexible Decoding: The library can decode map values into a wide range of Go data structures, including structs, slices, and maps.
- Customizable Behavior: The library provides various options and hooks to customize the decoding process, such as handling field tags, default values, and error handling.
- Performance: The library is designed to be efficient and fast, making it suitable for use in performance-critical applications.
- Extensive Documentation: The project has detailed documentation, including examples and usage guides, making it easy to get started and understand the library's capabilities.
Cons
- Limited Error Handling: While the library provides some error handling capabilities, the error messages can be somewhat cryptic, making it challenging to diagnose issues in complex data structures.
- Dependency on Reflection: The library relies heavily on Go's reflection capabilities, which can make it more difficult to understand and debug the underlying implementation.
- Lack of Strict Type Checking: The library's flexibility can also be a drawback, as it may not provide the same level of type safety as more rigid data binding approaches.
- Limited Support for Nested Structures: While the library can handle nested data structures, the complexity can increase as the depth of the nesting grows.
Code Examples
Here are a few examples of how to use the mitchellh/mapstructure
library:
- Decoding a Simple Map into a Struct:
type Person struct {
Name string
Age int
}
data := map[string]interface{}{
"name": "John Doe",
"age": 30,
}
var person Person
err := mapstructure.Decode(data, &person)
if err != nil {
// Handle error
}
fmt.Println(person) // Output: {John Doe 30}
- Decoding a Map with Nested Structures:
type Address struct {
Street string
City string
Country string
}
type Person struct {
Name string
Age int
Address Address
}
data := map[string]interface{}{
"name": "John Doe",
"age": 30,
"address": map[string]interface{}{
"street": "123 Main St",
"city": "Anytown",
"country": "USA",
},
}
var person Person
err := mapstructure.Decode(data, &person)
if err != nil {
// Handle error
}
fmt.Println(person) // Output: {John Doe 30 {123 Main St Anytown USA}}
- Decoding a Map with Custom Field Tags:
type Person struct {
FullName string `mapstructure:"full_name"`
Age int `mapstructure:"person_age"`
}
data := map[string]interface{}{
"full_name": "John Doe",
"person_age": 30,
}
var person Person
err := mapstructure.Decode(data, &person)
if err != nil {
// Handle error
}
fmt.Println(person) // Output: {John Doe 30}
Getting Started
To use the mitchellh/mapstructure
library in your Go project, follow these steps:
- Install the library using the Go package manager:
go get github.com/mitchellh/mapstructure
- Import the library in your Go code:
import "github.com/mitchellh/mapstructure"
- Use the
mapstructure.Decode()
function to decode a map into a Go struct:
data := map[string]interface{}{
"name": "John Doe",
"age": 30,
}
var person Person
err := mapstructure.Decode(data, &person)
if err != nil {
// Handle error
}
fmt.Println(person)
Competitor Comparisons
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
Pros of validator
- More comprehensive validation capabilities, including built-in validation rules
- Supports both struct and field-level validation
- Offers custom validation functions and error messages
Cons of validator
- Steeper learning curve due to more complex API
- May be overkill for simple struct-to-map conversions
- Requires additional tags for validation rules
Code Comparison
mapstructure:
type Person struct {
Name string `mapstructure:"name"`
Age int `mapstructure:"age"`
}
var m = map[string]interface{}{"name": "John", "age": 30}
var p Person
mapstructure.Decode(m, &p)
validator:
type Person struct {
Name string `validate:"required,min=2,max=50"`
Age int `validate:"required,gte=0,lte=120"`
}
validate := validator.New()
err := validate.Struct(person)
Summary
mapstructure focuses on decoding maps into structs, while validator provides extensive validation capabilities. mapstructure is simpler to use for basic conversions, but validator offers more robust data validation features. Choose mapstructure for straightforward struct population from maps, and validator when you need comprehensive input validation.
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
Pros of govalidator
- Focuses on data validation with a wide range of built-in validation functions
- Supports custom validation rules and error messages
- Provides utility functions for string manipulation and type checking
Cons of govalidator
- Limited to validation and doesn't offer advanced struct mapping capabilities
- May require more manual work for complex data transformations
- Less flexible for handling nested structures compared to mapstructure
Code Comparison
mapstructure:
type Person struct {
Name string `mapstructure:"name"`
Age int `mapstructure:"age"`
}
var m = map[string]interface{}{"name": "John", "age": 30}
var p Person
mapstructure.Decode(m, &p)
govalidator:
type User struct {
Name string `valid:"required"`
Email string `valid:"email"`
}
u := User{Name: "John", Email: "john@example.com"}
result, err := govalidator.ValidateStruct(u)
mapstructure excels at mapping between different data structures, especially when dealing with complex nested structures or interfaces. It's particularly useful for decoding configuration files or API responses into Go structs.
govalidator, on the other hand, specializes in data validation. It offers a wide range of built-in validators and allows for custom validation rules. While it doesn't provide the same level of struct mapping capabilities as mapstructure, it's more focused on ensuring data integrity and correctness.
Choose mapstructure for flexible data mapping and transformation, and govalidator for robust data validation and sanitization tasks.
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
Pros of ozzo-validation
- More flexible validation rules with built-in and custom validators
- Supports validation of nested structures and slices
- Provides detailed error messages for failed validations
Cons of ozzo-validation
- Requires more setup and code for basic validations
- Learning curve for custom validation rules
- May be overkill for simple data binding scenarios
Code Comparison
mapstructure:
type Person struct {
Name string `mapstructure:"name"`
Age int `mapstructure:"age"`
}
var m = map[string]interface{}{"name": "John", "age": 30}
var p Person
mapstructure.Decode(m, &p)
ozzo-validation:
type Person struct {
Name string
Age int
}
func (p Person) Validate() error {
return validation.ValidateStruct(&p,
validation.Field(&p.Name, validation.Required),
validation.Field(&p.Age, validation.Required, validation.Min(0)),
)
}
mapstructure focuses on decoding map data into structs, while ozzo-validation provides a more comprehensive validation framework. mapstructure is simpler to use for basic data binding, but ozzo-validation offers more control over validation rules and error reporting. Choose mapstructure for straightforward struct population, and ozzo-validation for complex validation scenarios with detailed error handling.
Utilities for Go structs
Pros of structs
- Simpler API for basic struct operations (e.g., converting to map, getting field names)
- Supports both struct tags and field names for flexible mapping
- Includes utility functions for working with struct fields (e.g., IsZero, HasZero)
Cons of structs
- Less powerful decoding capabilities compared to mapstructure
- Limited support for nested structs and complex data structures
- Fewer options for customizing the mapping process
Code Comparison
structs:
m := structs.Map(person)
names := structs.Names(person)
mapstructure:
var result Person
err := mapstructure.Decode(input, &result)
Key Differences
- structs focuses on struct-to-map conversions and field operations
- mapstructure specializes in decoding maps or JSON into structs
- structs has a more straightforward API for basic struct manipulations
- mapstructure offers more advanced decoding features and customization options
Use Cases
- Choose structs for simple struct-to-map conversions and basic field operations
- Opt for mapstructure when dealing with complex data structures or requiring advanced decoding capabilities
safe and easy casting from one type to another in Go
Pros of Cast
- Specialized in type conversion, offering a wide range of casting functions
- Simpler API for basic type conversions
- Includes additional utility functions like
ToTimeE
andToDurationE
Cons of Cast
- Less flexible for complex struct mapping scenarios
- Doesn't support custom decoding logic for specific fields
- Limited options for handling nested structures
Code Comparison
Cast:
value := cast.ToString(123)
number := cast.ToInt([]byte("456"))
Mapstructure:
var result MyStruct
err := mapstructure.Decode(input, &result)
Key Differences
Mapstructure focuses on decoding map-like structures into Go structs, offering more advanced features for complex mapping scenarios. It provides greater flexibility in handling nested structures and custom decoding logic.
Cast, on the other hand, specializes in straightforward type conversions between various Go types. It offers a simpler API for basic casting operations but lacks the advanced struct mapping capabilities of Mapstructure.
Choose Cast for simple type conversions and basic casting needs. Opt for Mapstructure when dealing with complex struct mapping, nested structures, or when you need more control over the decoding process.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
mapstructure
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.
Installation
Standard go get
:
$ go get github.com/mitchellh/mapstructure
Usage & Example
For usage and examples see the Godoc.
The Decode
function has examples associated with it there.
But Why?!
Go offers fantastic standard libraries for decoding formats such as JSON. The standard method is to have a struct pre-created, and populate that struct from the bytes of the encoded format. This is great, but the problem is if you have configuration or an encoding that changes slightly depending on specific fields. For example, consider this JSON:
{
"type": "person",
"name": "Mitchell"
}
Perhaps we can't populate a specific structure without first reading
the "type" field from the JSON. We could always do two passes over the
decoding of the JSON (reading the "type" first, and the rest later).
However, it is much simpler to just decode this into a map[string]interface{}
structure, read the "type" key, then use something like this library
to decode it into the proper structure.
Top Related Projects
:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
[Go] Package of validators and sanitizers for strings, numerics, slices and structs
An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
Utilities for Go structs
safe and easy casting from one type to another in Go
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot