How to convert Go struct to JSON?
Example
package main
import (
"fmt"
"encoding/json"
)
type Employee struct {
Name string `json:"empname"`
Number int `json:"empid"`
}
func main() {
emp := &Employee{Name: "Rocky",Number: 5454}
e, err := json.Marshal(emp)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(e))
}
Output
{"empname":"Rocky","empid":5454}
Most Helpful This Week
Find Type of Struct in Go Programming Language
Declaration of a struct type
Add Method to Struct Type
Nested Struct Type
Creating a Struct Instance Using a Struct Literal
Comparing Structs with the Different Values Assigned to Data Fields
Struct Instantiation using new keyword
Assign Default Value for Struct Field
What is Struct
Use Field Tags in the Definition of Struct Type
Struct Instantiation Using Pointer Address Operator
Copy Struct Type Using Value and Pointer Reference
Creating Instances of Struct Types