Go provides the encoding/json package that allows you to work with JSON data. JSON is a powerful and incredible data exchange format.

In this article, we will learn how you can parse JSON data using the encoding/json package.

Golang Unmarshal

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

In Go, the json.Unmarshal() method handles unmarshaling.

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 we perform 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:

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

This was a short guide that illustrates how to convert JSON data into a structure. To learn more, check our tutorial on Golang Marshal and Unmarshal.

Thanks for reading & Happy Coding!

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352b1a8d49.jpg" height="112" src="data:image/svg xml,” width=”112″>

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