Introduction to JSON Encoding
The Golang language already provides functions for JSON data conversion needs, namely we can use this function
func json.Marshal(interface{})
The parameters sent to the marshal function are in the form interface{} because we can use any data type to perform the conversion.
How to Implement
We will try to practice this way to better understand JSON encoding. You try to create a new project like previous projects. Suppose we create a folder learn-golang-json
.
Then initialize the Golang module with the command
go mod init github.com/santekno/learn-golang-json
Create a file main.go
to save the code that we will create and fill the file with the code below.
func LogJSON(data interface{}) string {
bytes, err := json.Marshal(data)
if err != nil {
panic(err)
}
return string(bytes)
}
In the function above that we created, we will convert the logging into JSON format. So that when we send any data format, it will immediately be encoded into JSON format according to JSON rules.
To test it, we need to make a unit test so that we understand more about how the JSON encode works and also that we are more accustomed to making unit tests when we are already coding.
package main
import (
"testing"
"github.com/go-playground/assert/v2"
)
type data struct {
FirstName string
MiddleName string
LastName string
}
func TestLogJSON(t *testing.T) {
type args struct {
data interface{}
}
tests := []struct {
name string
args args
want string
}{
{
name: "encode string",
args: args{
data: string("santekno"),
},
want: `"santekno"`,
},
{
name: "encode number",
args: args{
data: 2,
},
want: "2",
},
{
name: "encode boolean",
args: args{
data: true,
},
want: "true",
},
{
name: "encode array string",
args: args{
data: []string{"santekno", "ihsan"},
},
want: `["santekno","ihsan"]`,
},
{
name: "encode object",
args: args{
data: data{
FirstName: "Ihsan",
MiddleName: "Arif",
LastName: "Rahman",
},
},
want: `{"FirstName":"Ihsan","MiddleName":"Arif","LastName":"Rahman"}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, LogJSON(tt.args.data), tt.want)
})
}
}
In the unit test above we created several embedded data types. The data types tested above are in the form of string, number, boolean, array and object formats. So, all data types are supported by the JSON format, so we no longer need to be confused about what data types are not supported by JSON.