Golang JSON Marshal(encode) and Unmarshal(decode/parse) with examples
1 minsJSON (Javascript Object Notation) is a simple data interchange format widely used in http communication.
Go has built-in support for encoding and decoding JSON data. In this article, you’ll learn how to convert a Go type (native or struct) to JSON and vice versa. We’ll use the following structs in this article for demonstrating JSON encoding and decoding in Go -
type User struct {
Id int
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"-"`
Hobbies []string `json:"hobbies,omitempty"`
Address Address `json:"address"`
Attributes map[string]string `json:"attributes"`
}
type Address struct {
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
}
JSON Encoding (Marshaling): Convert GO types to JSON
You can use the Marshal()
function to marshal or serialize a Go type to JSON data:
func Marshal(v interface{}) ([]byte, error)
Following is an example -
package main
import (
"encoding/json"
"fmt"
)
func main() {
user := User{
Id: 1,
Name: "Rajeev Singh",
Email: "rajeevhub@gmail.com",
Password: "123456",
Hobbies: []string{"Coding", "Travelling", "Photography"},
Address: Address{
City: "Bangalore",
State: "Karnataka",
Country: "India",
},
Attributes: map[string]string{
"Twitter": "callicoder",
"Instagram": "rajeevhub",
},
}
jsonData, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(jsonData))
}
# Output
{"Id":1,"name":"Rajeev Singh","email":"rajeevhub@gmail.com","hobbies":["Coding","Travelling","Photography"],"address":{"city":"Bangalore","state":"Karnataka","country":"India"},"attributes":{"Instagram":"rajeevhub","Twitter":"callicoder"}}
JSON Decoding (Unmarshaling or Parsing): Convert JSON to Go type
To parse or deserialize a JSON string to a Go type, you can use the Unmarshal()
function:
func Unmarshal(data []byte, v interface{}) error
Here is an example of how to use the Unmarshal()
function:
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonData := `
{
"Id": 1,
"name": "Rajeev Singh",
"email": "rajeevhub@gmail.com",
"password": "123456",
"hobbies": [
"Coding",
"Travelling",
"Photography"
],
"address": {
"city": "Bangalore",
"state": "Karnataka",
"country": "India"
},
"attributes": {
"Instagram": "rajeevhub",
"Twitter": "callicoder"
}
}
`
var user User
err := json.Unmarshal([]byte(jsonData), &user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(user)
}
# Output
{1 Rajeev Singh rajeevhub@gmail.com [Coding Travelling Photography] {Bangalore Karnataka India} map[Instagram:rajeevhub Twitter:callicoder]}