How to convert Struct fields into Map String?
The below code snippet declares a struct type MyStruct with fields Name and Score. A map named myMap has string keys and an empty interface as value created.
Example
package main
import (
"encoding/json"
"fmt"
)
type MyStruct struct {
Name string
Score int
}
func main() {
ms := MyStruct{Name: "John", Score: 34}
var myMap map[string]interface{}
data, _ := json.Marshal(ms)
json.Unmarshal(data, &myMap)
fmt.Println(myMap["Name"])
fmt.Println(myMap["Score"])
}
John
34
Most Helpful This Week
Golang Program to print Triangle of Numbers
Cannot use <variable> (type <type>) as type <new-type> error in Golang
How to build a map of struct and append values to it?
Golang program to demonstrates how to encode map data into a JSON string.
Golang program for implementation of ZigZag Matrix
Go program to find TXT records of a domain
Sierpinski Carpet in Go Programming Language
How do you handle HTTP client server compression in Go?
Illustration of Sleeping Barber Problem in Golang
Example to use various String Functions in Go Language