Golang program to demonstrates how to encode map data into a JSON string.
The below example is to converts a map type into a JSON string. First we need to add the package encoding/json to the list of imports. Then Marshal function of the json package is used to encode Go values into JSON values.
Example
package main
import (
"fmt"
"encoding/json" // Encoding and Decoding Package
)
func main() {
// Create a map of key/value pairs and parses the data into JSON
emp := make(map[string]interface{})
emp["name"] = "Mark Taylor"
emp["jobtitle"] = "Software Developer"
emp["phone"] = map[string]interface{}{
"home": "123-466-799",
"office": "564-987-654",
}
emp["email"] = "markt@gmail.com"
// Marshal the map into a JSON string.
empData, err := json.Marshal(emp)
if err != nil {
fmt.Println(err.Error())
return
}
jsonStr := string(empData)
fmt.Println("The JSON data is:")
fmt.Println(jsonStr)
}
Output
The JSON data is:
{"email":"markt@gmail.com","jobtitle":"Software Developer","name":"Mark Taylor","phone":{"home":"123-466-799","office":"564-987-654"}}
Here is the syntax for Marshal functions in Go:
func Marshal(v interface{}) ([]byte, error)
Marshal function is good for producing JSON that could be returned in a network response, like a Restfult API. The function Marshal returns two values: the encoded JSON data as slice byte and an error value. Using Marshal , we can also encode the values of struct type as JSON values that will help us to quickly build JSON-based APIs.