Golang Json Marshal Example
Alex Garella
27 April 2022
The Go standard library offers a package that has all you need to perform JSON encoding and decoding. The encoding/json package. It allows you to do encoding of JSON data as defined in the RFC 7159. When working with data we usually want to encode some Go struct into a json string. However the Go standard library encoding/json package allows us to encode any data type into a JSON string. Let’s see some of the examples and how the json encoding works on some of the basic Go data types and how you can marshal json.
Here’s the definition of the json Marshal in the json encoding package
func Marshal(v interface{}) ([]byte, error)
We can effectively encode any type and we will get a byte slice as output and an error if there was any during the json marshalling.
JSON Marshal Int
a, _ := json.Marshal(28192)
fmt.Println(string(a)) // 20192
Integer types will be JSON marshalled into integer strings
JSON Marshal Bool
a, _ := json.Marshal(true)
fmt.Println(string(a)) // true
Same goes for boolean types that will be encoded to correspective booleans as string values
JSON Marshal Slice
a, _ := json.Marshal([]string{"foo", "bar", "baz"})
fmt.Println(string(a)) // ["foo","bar","baz"]
For slices we will get a JSON array instead
JSON Marshal Map
a, _ := json.Marshal(map[string]int{"foo": 1, "bar": 2, "baz": 3})
fmt.Println(string(a)) // {"bar":2,"baz":3,"foo":1}
Go maps will be marhsalled into JSON objects where keys of the map are keys of the JSON objects and values mapped to JSON object values, this allows you to build pretty dynamic structures without prior definition (unlike structs)
JSON Marshal Struct
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
Age int
Active bool
lastLoginAt string
}
func main() {
u, err := json.Marshal(User{Name: "Bob", Age: 10, Active: true, lastLoginAt: "today"})
if err != nil {
panic(err)
}
fmt.Println(string(u)) // {"Name":"Bob","Age":10,"Active":true}
}
This is a more complete example and it allows you to see how a struct is being JSON marshalled in Go. All the exported struct fields. Note that the field starting with lowercase lastLoginAt
is unexported and wont be shown in the final JSON marshal output.
JSON Marshal Struct with JSON Tags
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string `json:"full_name"`
Age int `json:"age,omitempty"`
Active bool `json:"-"`
lastLoginAt string
}
func main() {
u, err := json.Marshal(User{Name: "Bob", Age: 0, Active: true, lastLoginAt: "today"})
if err != nil {
panic(err)
}
fmt.Println(string(u)) // {"full_name":"Bob"}
}
This example allows us to see a couple of edge cases and features of JSON
- You can specify a JSON tag
json:"full_name"
and specify a custom name for your JSON field - When specifying
json:"<field name>,omitempty"
as a json tag, the field will be disarcarded in the JSON output if the value has a zero value. This is mostly used to discard optional JSON fields in the output - When specifying
json:"-"
as a json tag, the field will be removed altogether from the JSON output. This is used when you want to keep the field in your Go struct but not in your JSON output
Go JSON YouTube Tutorial
