Encode options
Options go to codec.MarshalWithOptions for one call, or to codec.NewEncoder
for an encoder you keep.
Layout
| option | effect |
|---|---|
Indent(n) | spaces per level of mapping nesting; DefaultIndentSpaces is 2 |
IndentSequence(bool) | indents sequence entries under their key |
Flow(bool) | flow style throughout |
UseLiteralStyleIfMultiline(bool) | a multiline string is written as a literal block, whatever it contains |
UseSingleQuote(bool) | prefers ' over " where a string needs quoting |
JSON() | writes JSON |
Encoding {"name": "x", "ports": [80, 443]}:
Indent does not move sequence entries. They sit at their key’s column
unless IndentSequence(true) is also set, so Indent(4) alone changes nothing
in a document whose only nesting is a sequence. With both:
Leaving fields out
| option | effect |
|---|---|
OmitEmpty() | as if every field carried ,omitempty |
OmitZero() | as if every field carried ,omitzero |
Both are the tag applied to everything, so they are the fallback for a type whose tags you do not control. Prefer the tag where you do.
Numbers
AutoInt() writes a float whose fractional part is zero as an integer.
map[string]float64{"a": 1.0} gives a: 1.0 by default and a: 1 with the
option.
Note
There is no decode counterpart, so AutoInt breaks the round trip on purpose: a
float64(1.0) written as 1 reads back as an integer.
Anchors
| option | effect |
|---|---|
WithSmartAnchor() | two map values sharing a pointer get an anchor on the first and aliases after; the key name becomes the anchor name, with a suffix on collision |
MarshalAnchor(fn) | calls fn with each *ast.AnchorNode as it is written |
Both find an anchor by the address its value stands at. A document decoded
and re-encoded therefore keeps its anchors only where the decode left one value
behind two names — which is what ShareAliases does. Without it, encoding writes
the shared subtree out twice.
Naming and custom types
WriteJSONTags(bool) and WriteInferredNames(bool) mirror the decode pair — see
Struct tags. UseJSONMarshaler() calls a type’s
MarshalJSON. CustomMarshaler[T] registers a
function for one type, for this encode only.
Comments
WithComment(cm) writes the comments in a CommentMap.