Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
11 Oct 2023 · 3 min read ·Article 52 / 119
Go

02 Encode JSON

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Introduction to JSON Encoding

The Golang language already provides functions for JSON data conversion needs, namely we can use this function

go
1func 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

bash
1go 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.

go
1func LogJSON(data interface{}) string {
2	bytes, err := json.Marshal(data)
3	if err != nil {
4		panic(err)
5	}
6
7	return string(bytes)
8}

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.

go
 1package main
 2
 3import (
 4	"testing"
 5
 6	"github.com/go-playground/assert/v2"
 7)
 8
 9type data struct {
10	FirstName  string
11	MiddleName string
12	LastName   string
13}
14
15func TestLogJSON(t *testing.T) {
16	type args struct {
17		data interface{}
18	}
19	tests := []struct {
20		name string
21		args args
22		want string
23	}{
24		{
25			name: "encode string",
26			args: args{
27				data: string("santekno"),
28			},
29			want: `"santekno"`,
30		},
31		{
32			name: "encode number",
33			args: args{
34				data: 2,
35			},
36			want: "2",
37		},
38		{
39			name: "encode boolean",
40			args: args{
41				data: true,
42			},
43			want: "true",
44		},
45		{
46			name: "encode array string",
47			args: args{
48				data: []string{"santekno", "ihsan"},
49			},
50			want: `["santekno","ihsan"]`,
51		},
52		{
53			name: "encode object",
54			args: args{
55				data: data{
56					FirstName:  "Ihsan",
57					MiddleName: "Arif",
58					LastName:   "Rahman",
59				},
60			},
61			want: `{"FirstName":"Ihsan","MiddleName":"Arif","LastName":"Rahman"}`,
62		},
63	}
64	for _, tt := range tests {
65		t.Run(tt.name, func(t *testing.T) {
66			assert.Equal(t, LogJSON(tt.args.data), tt.want)
67		})
68	}
69}

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.

Related Articles

💬 Comments