This repository demonstrates how to customize JSON field names in Go using struct tags. It showcases how to use Go's encoding/json
package to serialize and deserialize struct fields with custom names.
- This example covers how to use struct tags to customize JSON field names during encoding and decoding.
- It demonstrates defining a struct with custom JSON field names using the `json` struct tag.
package main
import (
"encoding/json"
"fmt"
)
type Person5 struct {
Name string `json:"full_name"`
Age int `json:"age"`
Country string `json:"country"`
}
func main() {
// This example demonstrates how to customize JSON field names using struct tags (json:"field_name")
person := Person5{
Name: "John Doe",
Age: 30,
Country: "USA",
}
jsonData, err := json.Marshal(person)
if err != nil {
fmt.Println("Error encoding JSON:", err)
return
}
fmt.Println(string(jsonData))
}
-
Make sure you have Go installed. If not, you can download it from here.
-
Clone this repository:
git clone https://github.com/Rapter1990/go_sample_examples.git
-
Navigate to the
005_custom_json_field_names
directory:cd go_sample_examples/030_json/005_custom_json_field_names
-
Run the Go program:
go run 005_custom_json_field_names.go
When you run the program, you should see the following output:
{"full_name":"John Doe","age":30,"country":"USA"}