This repository demonstrates how to encode Go structs into JSON format using Go's standard library package encoding/json
. It showcases the basic steps required to marshal Go data structures into JSON format for serialization.
- This example covers basic JSON encoding using Go structs and the `json.Marshal` function.
- It demonstrates how to convert a Go struct into JSON format, handling potential errors during the encoding process.
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
Country string
}
func main() {
// This example shows how to convert a Go struct into JSON format using json.Marshal
person := Person{
Name: "John",
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
001_basic_encoding_json
directory:cd go_sample_examples/030_json/001_basic_encoding_json
-
Run the Go program:
go run 001_basic_encoding_json.go
When you run the program, you should see the following output:
{"Name":"John","Age":30,"Country":"USA"}