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
Example to compare Println vs Printf
How to create Slice of Struct in Golang?
Undefined <variable/function> error in Golang
Go program to find Forward(A) record of a domain
How do you read cookies in an HTTP request with an HTTP client in Go?
Go program to find CNAME record of a domain
Golang Program to print Floyd's triangle
Go program to reading plain text files
How to Convert string to float type in Go?
Modernizing Legacy Applications: Critical Tips for Organizational Upgrades