programming

03 How to know JSON Object

Introduction to JSON Objects

In the previous article we studied encoding data such as string, number, boolean and other primitive types. But there is one case in the unit test which is made in the form of a struct object. So, this time we will study the objects of JSON in more depth. JSON data is in the form of objects and arrays, while the values can be objects again or directly data with other primitive types.

Example of a JSON object as below.

{
	"first_name":"Santekno",
	"middle_name": "Ihsan",
	"last_name":"Arif"
}

JSON objects in Golang can be represented in the form of the Struct data type, where each attribute in the JSON object is an attribute of the struct itself.

We try to represent the JSON object above into a struct structure like this

type Customer struct {
	FirstName string `json:"first_name"`
	MiddleName string `json:"middle_name"`
	LastName string `json:"last_name"`
}

In the struct above we see that there is an addition of json:"first_name" and another one which is also needed to change the name of the key of the JSON object. For example, in the JSON object we create a key first_name but we want to represent it in the Customer struct with the FirstName field. So this is like mapping a JSON key object to a field in the FirstName struct.

How to Implement JSON objects

For example, we will try to create a JSON object that we take from a struct that we create. Let’s try to do something.

type Customer struct {
	FirstName  string `json:"first_name"`
	MiddleName string `json:"middle_name"`
	LastName   string `json:"last_name"`
}

func GenerateobjekJSON(data Customer) string {
	bytes, err := json.Marshal(data)
	if err != nil {
		panic(err)
	}

	return string(bytes)
}

So we can see that creating a JSON object is the same as the function we created before, but we create a parameter with the struct Customer data type.

We will try to test the function that we have created using unit tests.

func TestGenerateObjectJSON(t *testing.T) {
	type args struct {
		data Customer
	}
	tests := []struct {
		name string
		args args
		want string
	}{
		{
			name: "success generate object JSON",
			args: args{
				data: Customer{
					FirstName:  "Santekno",
					MiddleName: "Ihsan",
					LastName:   "Arif",
				},
			},
			want: string(`{"first_name":"Santekno","middle_name":"Ihsan","last_name":"Arif"}`),
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := GenerateObjectJSON(tt.args.data); got != tt.want {
				t.Errorf("GenerateObjectJSON() = %v, want %v", got, tt.want)
			}
		})
	}
}

We can see that the results of json.Marshal will create a JSON object that has a key that has been created in the json tags in the struct.

comments powered by Disqus