Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. json.Marshal() / Unmarshal()

json.Marshal() / Unmarshal()

To convert between Go values and JSON, use the encoding/json package. Use json.Marshal() to encode a Go value into a JSON byte slice, and json.Unmarshal() to decode JSON into a Go value.

Syntax

// Encode a Go value into a JSON byte slice
data, err := json.Marshal(value)

// Decode a JSON byte slice into a Go value (pass a pointer for v)
err := json.Unmarshal(jsonByteSlice, &v)

// Add JSON tags to struct fields
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

Function List

FunctionDescription
json.Marshal(v)Returns a JSON-encoded byte slice of the Go value v.
json.MarshalIndent(v, prefix, indent)Returns pretty-printed JSON with indentation. Useful for debugging and display.
json.Unmarshal(data, v)Decodes a JSON byte slice and stores the result in v. Pass a pointer for v.

Sample Code

package main

import (
	"encoding/json"
	"fmt"
)

// Use JSON tags to specify the key names in the output
type User struct {
	Name  string `json:"name"`
	Age   int    `json:"age"`
	Email string `json:"email,omitempty"` // Omit if empty
}

func main() {
	// Encode a struct to JSON (Marshal)
	user := User{Name: "Tanaka", Age: 30}
	data, err := json.Marshal(user)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("JSON:", string(data))

	// Encode with pretty-printing (MarshalIndent)
	pretty, _ := json.MarshalIndent(user, "", "  ")
	fmt.Println("Pretty JSON:\n", string(pretty))

	// Decode JSON into a struct (Unmarshal)
	jsonStr := `{"name":"Sato","age":25,"email":"sato@example.com"}`
	var decoded User
	err = json.Unmarshal([]byte(jsonStr), &decoded)
	if err != nil {
		fmt.Println("Decode error:", err)
		return
	}
	fmt.Printf("Decoded: %+v\n", decoded)

	// Receive JSON into a map (when the structure is unknown)
	var m map[string]interface{}
	json.Unmarshal([]byte(jsonStr), &m)
	fmt.Println("Name:", m["name"])
}

Notes

JSON tags (written in backticks as `json:"name"`) let you map Go field names to JSON key names. If no tag is provided, the field name is used as-is.

Always pass a pointer as the second argument to json.Unmarshal(). Passing a non-pointer value will cause a runtime error. Also, struct fields that receive decoded JSON must be exported (start with an uppercase letter). Unexported fields are excluded from JSON. For processing large amounts of data, using json.Encoder / Decoder is more memory-efficient.

If you find any errors or copyright issues, please .