golang

Golang Marshal and Unmarshal

Marshaling refers to transforming an object into a specific data format that is suitable for transmission.

JSON is one of the most popular data interchange formats. It is simplistic, human-readable, and very flexible. It is an excellent choice for APIs and most data transfer. The device you have is likely using JSON to perform a specific task.

In such a case, learning how to work with JSON is important. In this guide, we will learn how to work.

Golang Marshal

The encoding and decoding JSON information in Go is provided by the encoding/json package. It is part of the standard library; hence you do not need to install it.

You will require to import it, though, before you can use it.

The econding/json package encodes any data type to a valid JSON string, as we will see in these examples.

Before discussing how to encode Go structs, let us start with basic data types.

JSON Marshal Function

The following describes the syntax for the Marshal function as defined in the package.

func Marshal(v interface{}) ([]byte, error)

The function takes any data type as the argument. The function returns a byte slice, and an error is encountered during the marshal process.

Marshal Int

We can marshal an integer type as shown in the example below:

package main
import (
    "encoding/json"
    "fmt"
    "reflect"
)
funcmain() {
    i := 100
    marshal_int, _ := json.Marshal(i)
    //check type
    fmt.Println("Before cast: ", reflect.TypeOf(marshal_int))
    fmt.Println("After cast: ", reflect.TypeOf(string(marshal_int)))
}

In the example above, we start by importing the required packages. We need the encoding/json, fmt, and the reflect package in our example.

We use the json.Marshal() method to marshal and integer value. You will notice that the function returns a unint8 (an 8-bit unsigned integer) or byte. We need to cast it to a string as shown in the output below:

$ go run marshall.go
Before cast:  []uint8
After cast:string

This returns an integer string.

Marshal String.

We can marshal a string type as shown in the example below:

funcmarshal_str() {
    marshaled_str, _ := json.Marshal("Linuxhint")
    fmt.Println("Marshaled string: ", marshaled_str)
}

If we run the above code, we should get the string marshaled into a slice of bytes as:

Marshaled string: [34 76 105 110 117 120 104 105 110 116 34]

Marshall Bool

You can also marshal a Boolean type using the marshal function. Consider the example below:

funcmarshal_bool() {
    marshaled_bool, _ := json.Marshal(false)
    fmt.Println(marshaled_bool)
}

Marshal Float

Marshal a floating type as shown:

funcmarshal_float() {
    marshaled_float, _ := json.Marshal(3.14159)
    fmt.Println(marshaled_float)
}

Marshal Slice

The example below illustrates how to marshal a slice in Go:

funcmarshal_slice() {
    slice_raw := []string{"Microsoft", "Google", "Amazon"}
    marshaled_slice, _ := json.Marshal(slice_raw)
    fmt.Println(string(marshaled_slice))
}

Marshal Struct

To marshal a struct in Go, consider the example below:

funcmarshal_struct() {
    type employee struct {
        Full_Name string
        Age       int
        Retired   bool
        Salary    int
    }
    marshal_struct, _ := json.Marshal(employee{Full_Name: "John Doe", Age: 32, retired: false, salary: 140000})
    fmt.Println(string(marshal_struct))
}

The example function above illustrates how to marshal a struct type in Go.

The resulting output is as shown:

{"Full_Name":"John Doe","Age":32,"Retired":false,"Salary":140000}

The above represents the struct marshaled into a valid JSON string.

Golang Unmarshal

Unmarshal is the contrary of marshal. It allows you to convert byte data into the original data structure.

In go, unmarshaling is handled by the json.Unmarshal() method.

Consider an example JSON string as:

{"Full_Name":"John Doe","Age":32,"Retired":false,"Salary":140000}

Let us start by creating a struct to match the byte code after performing the Unmarshal.

type User struct {
    Full_Name string `json:"Full_Name"`
    Age string `json:"Age"`
    Retired bool `json:"Retired"`
    Salary int `json:"Salary"`
}

The next step is to create the JSON string into byte code. Once we have the byte code, we can Unmarshal it into a struct.

user_info_bytes := []byte(user_info)

Once we have the byte code, we can unmarshall it into struct.

var employee User

json.Unmarshal(user_info_bytes, &employee)

Once we have the struct, we can access the values as:

fmt.Println(employee.Full_Name)
fmt.Println(employee.Age)
fmt.Println(employee.Retired)
fmt.Println(employee.Salary)

The above code should return:

John Doe

32

false

140000

The full source code is as shown below:

func unmarshal_struct() {
    user_info := `{"Full_Name":"John Doe","Age":32,"Retired":false,"Salary":140000}`

    type User struct {
        Full_Name string `json:"Full_Name"`
        Age       string `json:"Age"`
        Retired   bool   `json:"Retired"`
        Salary    int    `json:"Salary"`
    }
    user_info_bytes := []byte(user_info)
    var employee User
    json.Unmarshal(user_info_bytes, &employee)
    fmt.Println(employee.Full_Name)
    fmt.Println(employee.Age)
    fmt.Println(employee.Retired)
    fmt.Println(employee.Salary)
}

Conclusion

Marshal and Unmarshal represent an important requirement of data transformation. As programmers, it is important to familiarize ourselves on how to perform such operations. This tutorial serves that purpose with ease.

Thanks for reading & Happy Coding!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list