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:
Let us start by creating a struct to match the byte code after we perform the Unmarshal.
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.
Once we have the byte code, we can unmarshall it into struct.
json.Unmarshal(user_info_bytes, &employee)
Once we have the struct, we can access the values as:
fmt.Println(employee.Age)
fmt.Println(employee.Retired)
fmt.Println(employee.Salary)
The above code should return:
32
false
140000
The full source code is as shown below:
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!