Skip to content

Latest commit

 

History

History

005_custom_json_field_names

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Go Sample Example - Custom JSON Field Names

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.

📖 Information

  • 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.

💻 Code Example

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

🏃 How to Run

  1. Make sure you have Go installed. If not, you can download it from here.

  2. Clone this repository:

    git clone https://github.com/Rapter1990/go_sample_examples.git
  3. Navigate to the 005_custom_json_field_names directory:

    cd go_sample_examples/030_json/005_custom_json_field_names
  4. Run the Go program:

    go run 005_custom_json_field_names.go

📦 Output

When you run the program, you should see the following output:

{"full_name":"John Doe","age":30,"country":"USA"}