liveBook · Manning

Serialization

As explained in Learn Go with Pocket-Sized Projects

Marshal is an operation that converts a structured program value into an encoded byte sequence.

Serialization converts a structured program value into an encoded byte sequence. In Go, Marshal performs this conversion when no io.Writer is available, while Encoder writes to an io.Writer. section 4.5 section 6.5.4

Choose the encoding operation according to the data source or destination:

  • Call json.Marshal for a value that should become JSON bytes, such as a structured log record. section 4.5
  • Use an Encoder when writing JSON or XML to an io.Writer; use Marshal when no writer is available. section 6.5.4
  • Expose struct fields that the encoding package must read or write, and use tags to map fields to encoded names. section 4.5

Structured log record

Define a structure containing Level and Message, then pass a value of that type to encoding/json.Marshal to produce a JSON log message. Keeping those fields exported allows the json package to access them. section 4.5

{
   "time": "2022-31-10 23:06:30.148845Z",
   "level": "warning",
   "message": "platform not scaled up for request"
}

Inspect a structured JSON log containing time, level, and message fields. section 4.5

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains Marshal versus Encoder through API guidance and examples, while deferring broader encoding concepts to later treatment.
Examples
Uses JSON log records, a tagged person structure, and XML exchange-rate responses as concrete encoding and decoding examples.
What it assumes
Requires Go structures and field visibility; teaches that encoding functions cannot access unexported fields.
What you can do after
Apply it via encoding/json.Marshal or encoding/xml.Marshal when converting structured values without a writer.
How it connects
Connects serialization with JSON, XML, struct tags, exported fields, io.Writer, Encoder, Decoder, and Unmarshal.

Also explained in

Compare how 24 books explain serialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.