Json encoder: how to marshal data with go
How to encode a golang object to a JSON string using the build in golang json module encoding/json. You will see how to define the custom golang object struct, fill the data and marshal the object to json. You will also see how you can do the error handling in go. You can also check how to do the Json decoder here. Json is a string representation of the data. It can encode string, number or boolean information. Json is widely used to send, receive data or just for storing purpose.
Json struct
The Json data format is a simple string, containing information about the variables value and type. It can contain, array, string, number. To identify an array or object, you can simple checking the starting bracket. [ brackets rappresent an array, while { bracket rappresent an object.
Array of strings:
["some value", "some other value"]
Simple object:
{"some key" : "some value for the key", "some other key" : 10}
Code
Here is the simple way to encode a data struct to a json string. As input the marshal function requires the filled data struct, while as output it will give the json string and the error. You can check the error to be sure if the marshal encoding process was sucessfully by simply checking if is nil.
json, err := json.Marshal(data)
Example
In the example a simple data struct is defined and is converted to the json string format.
package main
import (
"encoding/json"
"fmt"
)
type Data struct {
Title string `json:"title"`
Description string `json:"description"`
}
func main() {
data := Data{
Title: "your title",
Description: "description",
}
if jsonData, err := json.Marshal(data); err == nil{
fmt.Println(string(jsonData))
}
}