liveBook · Manning

MarshalJSON

As explained in Go in Action, Second Edition

MarshalJSON is a method convention that customizes how a Go value is encoded as JSON.

MarshalJSON is a Go method convention for customizing how a value becomes JSON. It is useful when ordinary struct-field encoding cannot enforce output requirements such as redaction or transformation. section 10.5.1

A MarshalJSON method returns a JSON byte slice and an error. Inside it, marshal an anonymous structure containing the intended output fields; this avoids recursively invoking MarshalJSON on the receiver. section 10.5.1

Redacting configuration output

For a Config value, copy the public fields into a temporary structure and replace Host before calling json.Marshal: func (c Config) MarshalJSON() ([]byte, error) { temp := &struct { Name string `json:"name"`; Version string `json:"version"`; Debug bool `json:"debug"`; Port int `json:"port"`; Host string `json:"host"` }{c.Name, c.Version, c.Debug, c.Port, "[REDACTED]"}; return json.Marshal(temp) }. This keeps sensitive data out of logs or external JSON. section 10.5.1

How Go in Action, Second Edition covers it

How deep it goes
Demonstrates a complete redaction implementation and explains recursion avoidance, but defers broader interface and encoding internals.
Examples
Uses a Config structure whose Host field becomes [REDACTED] during JSON output.
What it assumes
Assumes Go structs and JSON marshaling, while demonstrating the custom Marshaler method convention from the standard library.
What you can do after
Build it from scratch by implementing a custom JSON encoder that transforms or redacts fields before serialization.
How it connects
Connects JSON marshaling with encoding/json, struct tags, custom serialization, and sensitive-data sanitization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.