liveBook · Manning

Json.Marshal

As explained in Go in Action, Second Edition

json.Marshal is a Go standard-library function that encodes a Go value as a JSON-formatted byte sequence.

json.Marshal encodes a Go value as JSON bytes, making Go structs usable in configuration tools and other systems that exchange JSON data. Struct tags map Go fields to JSON keys, while exported fields remain accessible to encoding/json. section 10.5.1

Practical serialization depends on a few design choices:

  • Define a Go struct that mirrors the JSON shape, using tags such as `json:"name"`, `omitempty`, or `-` to rename, omit, or exclude fields. section 10.5.1
  • Implement `MarshalJSON` when serialized output needs custom behavior, such as redacting a sensitive field before delegating to `json.Marshal`. section 10.5.1
  • Use the Go struct as an intermediate representation when converting between JSON and XML, validating and normalizing data before marshaling the requested format. section 10.5.2

Redacting a configuration field during marshaling

A `Config` value can implement `MarshalJSON` by copying its fields into an anonymous struct, replacing `Host` with `"[REDACTED]"`, and returning `json.Marshal(temp)`. The anonymous struct prevents recursive calls to the custom method while preserving the desired JSON keys. section 10.5.1

Listing 10.16 config.json: Configuration defined in JSON format
{
    "name": "myapp",
    "version": "1.0.0",
    "debug": false,
    "port": 8080,
    "host": "localhost"
}

Inspect the concrete JSON configuration shape that the Go `Config` structure represents. section 10.5.1

How Go in Action, Second Edition covers it

How deep it goes
Demonstrates struct tags, custom MarshalJSON behavior, redaction, and format conversion without detailing exhaustive encoding rules.
Examples
Uses a server configuration with name, version, debug, port, and host fields, including a custom serializer that redacts the host.
What it assumes
Assumes Go structs and values, while teaching exported fields, JSON struct tags, and custom serialization patterns.
What you can do after
Apply it via encoding/json to serialize Go structs and customize output through MarshalJSON.
How it connects
Connects JSON marshaling with encoding/json, json.Unmarshal, struct tags, custom marshaling, and XML marshaling.

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.