In Go, you can customize field names during JSON encoding and decoding by using struct tags.
When encoding a struct to JSON, you can specify custom field names using the json
struct tag. The json
tag allows you to provide instructions to the JSON encoder about how to serialize the struct field.
For example:
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Age int `json:"age"`
}
In the above example, the field names in the resulting JSON will be "first_name", "last_name", and "age". If you omit the json
struct tag, the field name in the resulting JSON will be the same as the struct field name.
When decoding JSON into a struct, you can also use the json
struct tag to map JSON field names to struct fields. This allows you to handle situations where the JSON field names are different from the struct field names.
For example:
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Age int `json:"age"`
}
In this case, if the JSON contains fields named "first_name", "last_name", and "age", they will be correctly mapped to their corresponding struct fields during decoding.
You can also use the struct tag json:"-"
to ignore fields during encoding and decoding. This can be useful when you want to exclude certain fields from being serialized or deserialized.
In conclusion, you can customize field names during JSON encoding and decoding in Go by using the json
struct tag.