0
0
GoHow-ToBeginner · 3 min read

How to Marshal JSON in Go: Simple Guide with Examples

In Go, you use the json.Marshal function from the encoding/json package to convert Go data structures into JSON format. This function returns the JSON as bytes and an error if something goes wrong. You can then convert the bytes to a string to see the JSON output.
📐

Syntax

The basic syntax to marshal JSON in Go is:

  • json.Marshal(v interface{}) ([]byte, error): Converts the Go value v into JSON bytes.
  • The returned []byte contains the JSON data.
  • The error indicates if the marshaling failed.

You usually convert the bytes to a string to print or use the JSON.

go
jsonData, err := json.Marshal(yourData)
if err != nil {
    // handle error
}
jsonString := string(jsonData)
💻

Example

This example shows how to marshal a simple Go struct into JSON and print it as a string.

go
package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "Alice", Age: 30}
    jsonData, err := json.Marshal(p)
    if err != nil {
        fmt.Println("Error marshaling JSON:", err)
        return
    }
    fmt.Println(string(jsonData))
}
Output
{"Name":"Alice","Age":30}
⚠️

Common Pitfalls

Common mistakes when marshaling JSON in Go include:

  • Not exporting struct fields: Only fields starting with uppercase letters are included in JSON.
  • Ignoring the error returned by json.Marshal.
  • Expecting pretty-printed JSON without using json.MarshalIndent.

Example of a struct with unexported fields that won't appear in JSON:

go
package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    name string // unexported, will NOT appear in JSON
    Age  int
}

func main() {
    p := Person{name: "Bob", Age: 25}
    jsonData, err := json.Marshal(p)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(string(jsonData)) // Output: {"Age":25}
}
Output
{"Age":25}
📊

Quick Reference

FunctionDescription
json.Marshal(v interface{})Converts Go value to JSON bytes
json.MarshalIndent(v interface{}, prefix, indent string)Converts Go value to pretty-printed JSON bytes
json.Unmarshal(data []byte, v interface{})Parses JSON bytes into Go value

Key Takeaways

Use json.Marshal to convert Go data to JSON bytes.
Only exported struct fields (uppercase names) are included in JSON output.
Always check the error returned by json.Marshal.
Use string() to convert JSON bytes to a readable string.
Use json.MarshalIndent for pretty-printed JSON.