Member-only story

Mastering JSON in Go A Comprehensive Guide to Marshaling and Unmarshaling

Ron Liu
8 min readFeb 25, 2024

Introduction

Golang is increasingly popular for backend services, where JSON stands as the pivotal data format for communication. Its robust built-in support for JSON, a universally accepted data interchange format, is a key strength. Mastery of JSON marshaling and unmarshaling — the conversion of Go data structures to JSON and back — is essential for developers engaged in building web APIs, microservices, and any applications that necessitate data exchange.

Let’s give a simple example to marshal and unmarshal JSON in Go.


package main

import (
"encoding/json"
"fmt"
"log"
)

type User struct {
Name string `json:"name"`
Age int `json:"age"`
}

// marshalUser takes a User struct and returns its JSON representation as a string.
func marshalUser(user User) string {
userJSON, err := json.Marshal(user)
if err != nil {
log.Fatalf("JSON marshaling failed: %s", err)
}
return string(userJSON)
}

// unmarshalUser takes a JSON string and returns a User struct.
func unmarshalUser(userJSON string) User {
var user User
err := json.Unmarshal([]byte(userJSON), &user)
if err != nil {
log.Fatalf("JSON unmarshaling failed: %s", err)
}
return user
}

func main() {
// Original user instance.
originalUser := User{Name: "John Doe", Age: 30}

// Marshal the user to JSON.
userJSON := marshalUser(originalUser)
fmt.Println("Marshaled JSON:", userJSON)

//…

--

--

Ron Liu
Ron Liu

No responses yet