RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 15: Go and JSON – Talking to the Outside World 🌍

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

Have you ever worked with APIs in JavaScript or PHP?

You probably dealt with JSON — it's like the universal language of data exchange between apps.

In Go, working with JSON is easy, but you need to tell Go how to translate between your structs and JSON format.

Let’s go!

type User struct {
  Name  string `json:"name"`
  Email string `json:"email"`
}

🔍 The `json:"name"` tag tells Go:

"Hey, when you turn this into JSON, use name instead of Name."

package main
import (
  "encoding/json"
  "fmt"
)
type User struct {
  Name  string `json:"name"`
  Email string `json:"email"`
}
func main() {
  user := User{Name: "Ashraf", Email: "ashraf@example.com"}
  jsonData, _ := json.Marshal(user)
  fmt.Println(string(jsonData))
}

Output:

{"name":"Ashraf","email":"ashraf@example.com"}

Boom! That’s your struct, JSON-style.

jsonStr := `{"name":"Ashraf","email":"ashraf@example.com"}`
var user User
_ = json.Unmarshal([]byte(jsonStr), &user)
fmt.Println(user.Name)  // Ashraf
fmt.Println(user.Email) // ashraf@example.com

You just parsed JSON into a Go struct. 🚀

  • Communicate with web APIs (like weather, maps, or your backend!)

  • Save settings/configs

  • Store structured data

type Profile struct {
  User   User
  Active bool `json:"active"`
}

And Go will happily encode/decode it all.

Go only exports fields that start with a capital letter.

type Person struct {
  name string // won't be included in JSON!
}

So always capitalize struct fields if they need to be JSON’d.

  • Use json.Marshal() to encode

  • Use json.Unmarshal() to decode

  • Tags like json:"name" help map JSON keys

  • Only capitalized fields are included

No posts

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.