Go has a feature to create a user-defined type with struct
. Go also allows the program to specify meta-information with structure field.
This meta-information is called Tags. A tag usually helps in packaging/unpacking a user-defined type structure
.
package main
import (
"encoding/json"
"fmt"
)
type Test struct {
// json tags indicate the key name to use in json data
Name string `json:"myname"`
Country string `json:"region"`
}
func main() {
// The order of json need not match the order of structure fields.
p := map[string]string{"region": "earth", "myname": "hello"}
marshalled, err := json.Marshal(p)
fmt.Println(marshalled, err)
// get the var back from marshalled data
var m Test
json.Unmarshal(marshalled, &m)
fmt.Printf("name=%v\n", m.Name)
fmt.Printf("name=%v\n", m.Country)
}
Why should I use json tags
- The benefit of json tags is the flexibility to marshal with either a JSON or a struct.
- JSON input for marshaling is convenient and flexible with elements ordering.
Reference
Categories: development