programming

07 How To Use Maps

Map Use

When we use JSON we sometimes encounter cases of dynamic JSON data, which means that the attributes formed by JSON are uncertain, can increase or decrease and are not even fixed. So in cases like this, if we unmarshal using Struct, it will be difficult because in the struct we have to define all the attributes.

In this case there is another way, namely we can use the map[string]interface{} data type. By using this map, the attribute will automatically become a key in the map and a value becomes a JSON value in the map, but the value here is in the form of an interface so there needs to be another conversion manually if you want to retrieve the value.

In this map data type, JSON tags no longer apply or will no longer be supported because all the JSON keys will become keys in the map which cannot be aliased.

Example of Using Maps

Let’s try to demonstrate how we use a map to convert from JSON below.

func ConvertMapJSON(data string) map[string]interface{} {
	var result map[string]interface{}
	err := json.Unmarshal([]byte(data), &result)
	if err != nil {
		panic(err)
	}

	return result
}

The function that we have created above is how we convert json data into a map, the result of which will be map[string]interface.

We also add unit tests to test whether the function we have created meets expectations or not.

func TestConvertMapJSON(t *testing.T) {
	type args struct {
		data string
	}
	tests := []struct {
		name string
		args args
		want map[string]interface{}
	}{
		{
			name: "success convert map JOSN",
			args: args{
				data: string(`{"first_name":"Santekno","middle_name":"Ihsan","last_name":"Arif"}`),
			},
			want: map[string]interface{}{
				"first_name":  "Santekno",
				"middle_name": "Ihsan",
				"last_name":   "Arif",
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := ConvertMapJSON(tt.args.data); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("ConvertMapJSON() = %v, want %v", got, tt.want)
			}
		})
	}
}
comments powered by Disqus