Documentation
¶
Overview ¶
Package codec converts between YAML documents and Go values, with options.
Marshal and Unmarshal convert one document. NewEncoder and NewDecoder write and read a stream of documents, one for each call to Encoder.Encode or Decoder.Decode. ValueToNode and NodeToValue convert between a Go value and an github.com/go-openapi/go-yaml/ast tree.
These functions take options: an EncodeOption or a DecodeOption sets them for one call or one stream. The root package's Marshal and Unmarshal take none.
Struct fields ¶
A struct maps to a mapping of its exported fields. A field is named after its `yaml` tag, or after its Go name lowercased, as in go.yaml.in/yaml/v3. Marshal lists the tag's flags.
Three option pairs read and write struct fields as encoding/json does:
- UseJSONTags and WriteJSONTags read the `json` tag where a field has no `yaml` tag, and promote the fields of an untagged embedded struct.
- UseInferredNames and WriteInferredNames name an untagged field after its Go name, verbatim.
- OmitEmpty skips the fields encoding/json's omitempty skips, and OmitZero the fields its omitzero skips.
Types that encode or decode themselves ¶
A type implements Marshaler to return its YAML text, and Unmarshaler to receive it. NodeUnmarshaler receives the ast.Node instead, with its comments and positions. GoYAMLMarshaler and GoYAMLUnmarshaler have the shapes github.com/go-yaml/yaml expects, so that types written for that library work unchanged.
A type written for go.yaml.in/yaml/v3, whose method is UnmarshalYAML(*yaml.Node) error, is decoded through that method too. The decoder builds the yaml.Node from the document by reflection, so this module does not import v3. A field of type yaml.Node, or *yaml.Node, receives the node itself, and the encoder writes such a field, or a *yaml.Node a MarshalYAML method returns, as the YAML it describes. Neither direction carries comments.
To change how a type you do not own is encoded or decoded, pass CustomMarshaler or CustomUnmarshaler, or call RegisterCustomMarshaler or RegisterCustomUnmarshaler once for every encoder and decoder.
Values with no Go equivalent ¶
A Go map loses the order of a mapping, and cannot tell apart some keys that YAML holds apart. MapSlice keeps both, and UseOrderedMap decodes every untyped mapping into one. MapSliceSeq reads and writes the "!!omap" tag. Base64 holds a "!!binary" scalar, and RawMessage holds an encoded value whose decoding waits.
A Go value has no place for a comment. CommentToMap collects a document's comments into a CommentMap while decoding, and WithComment writes them back while encoding.
JSON ¶
ToJSON converts a YAML document to the JSON holding the same values, and ToJSONTokens hands the same conversion over token by token. FromJSON converts JSON to YAML. None of them goes through a Go value, so a number keeps its digits and a mapping its order.
Errors ¶
Errors carry a position in the document, and match the kinds the github.com/go-openapi/go-yaml/errors package declares, such as errors.ErrDuplicateKey or errors.ErrTypeMismatch, through errors.Is.
Index ¶
- Constants
- func FromJSON(src []byte, opts ...ast.RenderOption) ([]byte, error)
- func FromJSONTokens(tokens iter.Seq[JSONToken], opts ...ast.RenderOption) ([]byte, error)
- func Marshal(v any, opts ...EncodeOption) ([]byte, error)
- func NodeToValue(node ast.Node, v any, opts ...DecodeOption) error
- func RegisterCustomMarshaler[T any](marshaler func(T) ([]byte, error))
- func RegisterCustomUnmarshaler[T any](unmarshaler func(*T, []byte) error)
- func ToJSON(src []byte, opts ...parser.Option) ([]byte, error)
- func Unmarshal(data []byte, v any, opts ...DecodeOption) error
- func ValueToNode(v any, opts ...EncodeOption) (ast.Node, error)
- type Base64
- type Comment
- type CommentMap
- type CommentPosition
- type DecodeOption
- func AllowDuplicateMapKey() DecodeOption
- func AllowFieldPrefixes(prefixes ...string) DecodeOption
- func CommentToMap(cm CommentMap) DecodeOption
- func CustomUnmarshaler[T any](unmarshaler func(*T, []byte) error) DecodeOption
- func DisallowUnknownField() DecodeOption
- func RecursiveDir(isRecursive bool) DecodeOption
- func ReferenceDirs(dirs ...string) DecodeOption
- func ReferenceFiles(files ...string) DecodeOption
- func ReferenceReaders(readers ...io.Reader) DecodeOption
- func ShareAliases() DecodeOption
- func Strict() DecodeOption
- func UseInferredNames(use bool) DecodeOption
- func UseJSONTags(use bool) DecodeOption
- func UseJSONUnmarshaler() DecodeOption
- func UseOrderedMap() DecodeOption
- func UseStringKeys() DecodeOption
- func Validator(validate func(any) error) DecodeOption
- func WithParserOptions(opts ...parser.Option) DecodeOption
- type Decoder
- type EncodeOption
- func AutoInt() EncodeOption
- func CustomMarshaler[T any](marshaler func(T) ([]byte, error)) EncodeOption
- func Flow(isFlowStyle bool) EncodeOption
- func Indent(spaces int) EncodeOption
- func IndentSequence(indent bool) EncodeOption
- func JSON() EncodeOption
- func MarshalAnchor(callback func(*ast.AnchorNode, any) error) EncodeOption
- func OmitEmpty() EncodeOption
- func OmitZero() EncodeOption
- func SkipDuplicateMapKey() EncodeOption
- func UseJSONMarshaler() EncodeOption
- func UseLiteralStyleIfMultiline(useLiteralStyleIfMultiline bool) EncodeOption
- func UseSingleQuote(sq bool) EncodeOption
- func WithComment(cm CommentMap) EncodeOption
- func WithSmartAnchor() EncodeOption
- func WriteInferredNames(write bool) EncodeOption
- func WriteJSONTags(write bool) EncodeOption
- type Encoder
- type GoYAMLMarshaler
- type GoYAMLUnmarshaler
- type IsZeroer
- type JSONToken
- type JSONTokenKind
- type JSONTokens
- func (s *JSONTokens) AppendPath(dst []byte) []byte
- func (s *JSONTokens) Budget(tokens int) *JSONTokens
- func (s *JSONTokens) Depth() int
- func (s *JSONTokens) Err() error
- func (s *JSONTokens) OneDocument() *JSONTokens
- func (s *JSONTokens) Path() string
- func (s *JSONTokens) Tokens() iter.Seq[JSONToken]
- type MapItem
- type MapSlice
- func (s MapSlice) All() iter.Seq2[any, any]
- func (s MapSlice) At(i int) MapItem
- func (s *MapSlice) Delete(key any) bool
- func (s MapSlice) Get(key any) (any, bool)
- func (s MapSlice) Keys() iter.Seq[any]
- func (s MapSlice) Len() int
- func (s MapSlice) MarshalJSON() ([]byte, error)
- func (s *MapSlice) Set(key, value any) error
- func (s MapSlice) ToMap() map[any]any
- func (s *MapSlice) UnmarshalJSON(b []byte) error
- func (s MapSlice) Values() iter.Seq[any]
- type MapSliceSeq
- func (s MapSliceSeq) All() iter.Seq2[any, any]
- func (s MapSliceSeq) At(i int) MapItem
- func (s *MapSliceSeq) Delete(key any) bool
- func (s MapSliceSeq) Get(key any) (any, bool)
- func (s MapSliceSeq) Keys() iter.Seq[any]
- func (s MapSliceSeq) Len() int
- func (s MapSliceSeq) MarshalJSON() ([]byte, error)
- func (s *MapSliceSeq) Set(key, value any) error
- func (s MapSliceSeq) ToMap() map[any]any
- func (s *MapSliceSeq) UnmarshalJSON(b []byte) error
- func (s MapSliceSeq) Values() iter.Seq[any]
- type Marshaler
- type NodeUnmarshaler
- type RawMessage
- type Unmarshaler
Examples ¶
Constants ¶
const (
// DefaultIndentSpaces gives the number of spaces of each indentation level, unless [Indent] sets another.
DefaultIndentSpaces = 2
)
Variables ¶
This section is empty.
Functions ¶
func FromJSON ¶
func FromJSON(src []byte, opts ...ast.RenderOption) ([]byte, error)
FromJSON converts a JSON document to YAML in block style.
It reads src with the JSON lexer of github.com/go-openapi/core/json, so a document not written as JSON returns github.com/go-openapi/go-yaml/errors.ErrNotJSONSyntax, and a repeated member name returns github.com/go-openapi/go-yaml/errors.ErrDuplicateKey. It writes each value through an ast.Stream as the lexer reads it. Neither keeps what it has passed, so apart from its output, FromJSON holds memory in proportion to the document's nesting depth, not its length.
The YAML holds what the JSON wrote. A number keeps its text, such as "1e3", "-0" or a 20-digit integer, and reads back as a YAML 1.2 number. Member order is kept. A string is written as Marshal writes a Go string: plain where the plain text reads back as that string, quoted otherwise, so "yes", "1" and "null" stay quoted, and a string over several lines as a "|" block.
opts lay the YAML out: ast.WithIndent and ast.WithIndentSequence.
func FromJSONTokens ¶
FromJSONTokens writes the YAML for a sequence of JSON tokens, as FromJSON writes it for the JSON text they come from.
It takes the tokens of any JSON reader that yields them in document order, as JSONTokens.Tokens does, with no token for a "," or a ":". It checks their order, and returns an error wrapping github.com/go-openapi/go-yaml/errors.ErrDuplicateKey for a key repeated in one object, as FromJSON does: YAML has no mapping with two equal keys. Keys are compared as the tokens hold them, after unescaping, with no Unicode normalization. A reader that stops on an error leaves a collection open, and FromJSONTokens then returns ast.ErrStreamOrder: check the reader's own error first, since it names the fault.
opts lay the YAML out: ast.WithIndent and ast.WithIndentSequence.
func Marshal ¶
func Marshal(v any, opts ...EncodeOption) ([]byte, error)
Marshal returns the YAML encoding of v, as one document.
A struct is written as a mapping of its exported fields. A field is written under its name lowercased, or under the name its `yaml` tag gives. Two fields that end up with one name are an error.
The tag reads `yaml:"[name][,flag...]"`, and a field tagged "-" is skipped. The flags are:
omitempty skip a zero number, a false bool, an empty string, a nil pointer or interface, an empty slice or map,
a value whose IsZero method returns true (see [IsZeroer]), and a struct whose exported fields would
all be skipped. This takes in part of encoding/json's omitzero as well as its omitempty:
see https://github.com/goccy/go-yaml/issues/695.
omitzero skip the field as encoding/json's omitzero does: where IsZero returns true for a type with that
method, and otherwise where the value is the zero value of its type.
flow write the value in flow style: [a, b] and {k: v}.
inline write the fields of a struct, or the keys of a map, into the mapping around it. A map's keys must not
repeat the names of the other fields.
anchor write the value with an anchor, named after the field lowercased. anchor=name sets the name.
alias write an alias in place of the value. alias=name names the anchor. Without a name the field must be a
pointer, and the alias names the anchor written for the same address.
For example:
type T struct {
F int `yaml:"a,omitempty"`
B int
}
codec.Marshal(&T{B: 2}) // returns "b: 2\n"
codec.Marshal(&T{F: 1}) // returns "a: 1\nb: 0\n"
Options apply to this call only. Use NewEncoder to write a stream of documents.
Example ¶
var slow SlowMarshaler
slow.A = "Hello slow poke"
slow.B = 100
buf, err := codec.Marshal(slow)
if err != nil {
panic(err.Error())
}
fmt.Println(string(buf))
var fast FastMarshaler
fast.A = "Hello speed demon"
fast.B = 100
buf, err = codec.Marshal(fast)
if err != nil {
panic(err.Error())
}
fmt.Println(string(buf))
text := TextMarshalerContainer{
Field: 11,
}
buf, err = codec.Marshal(text)
if err != nil {
panic(err.Error())
}
fmt.Println(string(buf))
Output: tags: - slow-marshaler a: Hello slow poke b: 100 tags: - fast-marshaler a: Hello speed demon b: 100 field: "13"
Example (ExplicitAnchorAlias) ¶
package main
import (
"fmt"
"github.com/go-openapi/go-yaml/codec"
)
func main() {
type T struct {
A int
B string
}
var v struct {
C *T `yaml:"c,anchor=x"`
D *T `yaml:"d,alias=x"`
}
v.C = &T{A: 1, B: "hello"}
v.D = v.C
bytes, err := codec.Marshal(v)
if err != nil {
panic(err)
}
fmt.Println(string(bytes))
}
Output: c: &x a: 1 b: hello d: *x
Example (ImplicitAnchorAlias) ¶
package main
import (
"fmt"
"github.com/go-openapi/go-yaml/codec"
)
func main() {
type T struct {
I int
S string
}
var v struct {
A *T `yaml:"a,anchor"`
B *T `yaml:"b,anchor"`
C *T `yaml:"c"`
D *T `yaml:"d"`
}
v.A = &T{I: 1, S: "hello"}
v.B = &T{I: 2, S: "world"}
v.C = v.A // C has same pointer address to A
v.D = v.B // D has same pointer address to B
bytes, err := codec.Marshal(v)
if err != nil {
panic(err)
}
fmt.Println(string(bytes))
}
Output: a: &a i: 1 s: hello b: &b i: 2 s: world c: *a d: *b
Example (Node) ¶
package main
import (
"fmt"
"github.com/go-openapi/go-yaml/ast"
"github.com/go-openapi/go-yaml/codec"
)
func main() {
type T struct {
Text ast.Node `yaml:"text"`
}
stringNode, err := codec.ValueToNode("node example")
if err != nil {
panic(err)
}
bytes, err := codec.Marshal(T{Text: stringNode})
if err != nil {
panic(err)
}
fmt.Println(string(bytes))
}
Output: text: node example
func NodeToValue ¶
func NodeToValue(node ast.Node, v any, opts ...DecodeOption) error
NodeToValue decodes node into the value v points to, as Decoder.DecodeFromNode does.
Example ¶
package main
import (
"fmt"
"github.com/go-openapi/go-yaml/codec"
"github.com/go-openapi/go-yaml/parser"
)
func main() {
f, err := parser.ParseBytes([]byte("text: node example"))
if err != nil {
panic(err)
}
var v struct {
Text string `yaml:"text"`
}
if err := codec.NodeToValue(f.Docs[0].Body, &v); err != nil {
panic(err)
}
fmt.Println(v.Text)
}
Output: node example
func RegisterCustomMarshaler ¶
RegisterCustomMarshaler makes every encoder encode a T with marshaler, which returns the YAML text to write, in place of any other encoding of T. Use CustomMarshaler to set it for one encoder only.
Where T implements MarshalYAML on a pointer receiver, give *T as the type parameter. A CustomMarshaler option for the same type takes precedence.
func RegisterCustomUnmarshaler ¶
RegisterCustomUnmarshaler makes every decoder decode a T with unmarshaler, which receives the YAML text of the node, in place of any other decoding of T. The text is the one an Unmarshaler receives. Use CustomUnmarshaler to set it for one decoder only.
A CustomUnmarshaler option for the same type takes precedence.
func ToJSON ¶
ToJSON converts a YAML document to the JSON that holds the same values.
ToJSON writes the tokens of ToJSONTokens into one buffer, and adds the commas and colons the tokens leave out. The two converters read a document the same way: they resolve the same aliases, merges and tags, and reject the same documents.
For a stream of several documents, ToJSON converts the first, as Unmarshal decodes the first. It still reads the others, and returns an error if one of them cannot be converted.
opts go to the parser. parser.WithLaxTags is the one that changes the output: a scalar whose tag names a type it cannot hold converts to its text, so "k: !!int abc" gives {"k":"abc"} instead of an error. Pass it to every reader of the same document, so that they agree.
parser.WithJSONCompatible is always on: a document holding a value JSON cannot write, such as an infinity or a collection used as a key, returns an error.
Under parser.WithAllowDuplicateMapKey, a repeated key keeps its first value, as in ToJSONTokens. A decoder under AllowDuplicateMapKey keeps the last.
func Unmarshal ¶
func Unmarshal(data []byte, v any, opts ...DecodeOption) error
Unmarshal decodes the first document of data into the value v points to.
A mapping fills a struct's exported fields, matched by the names Marshal writes: the field name lowercased, or the name its `yaml` tag gives. See Marshal for the tag and its flags. Two fields that end up with one name are an error.
For example:
type T struct {
F int `yaml:"a,omitempty"`
B int
}
var t T
codec.Unmarshal([]byte("a: 1\nb: 2"), &t)
A value that does not fit its field, such as "a: x" into an int, is skipped and decoding goes on, as encoding/json does. Unmarshal returns the first such error, which matches github.com/go-openapi/go-yaml/errors.ErrTypeMismatch, and v holds everything decoded around it: the fields after it, and the parts of a nested struct, slice or map read before it.
Options apply to this call only. Use NewDecoder to read every document of a stream.
Example (YAMLTags) ¶
package main
import (
"fmt"
"log"
"github.com/go-openapi/go-yaml/codec"
)
func main() {
yml := `---
foo: 1
bar: c
A: 2
B: d
`
var v struct {
A int `json:"A" yaml:"foo"`
B string `json:"B" yaml:"bar"`
}
if err := codec.Unmarshal([]byte(yml), &v); err != nil {
log.Fatal(err)
}
fmt.Println(v.A)
fmt.Println(v.B)
}
Output: 1 c
func ValueToNode ¶
func ValueToNode(v any, opts ...EncodeOption) (ast.Node, error)
ValueToNode returns the AST node that Marshal would write for v, without rendering it.
Types ¶
type Base64 ¶
type Base64 string
Base64 holds the base64 text of a "!!binary" scalar, as an any destination decodes it. Base64.Bytes returns the bytes.
It holds the text, not the bytes, for three reasons:
- The text is comparable, so a "!!binary" scalar can key a mapping. A []byte cannot, because Go hashes no slice.
- It survives a round trip: a Base64 tells the encoder to write "!!binary", where a string or a []byte does not.
- JSON writes binary as base64 text, so ToJSON and a decode followed by a JSON encode write the same thing.
The underlying type is string, so you can compare two values, use one as a map key, and print one without decoding anything. RFC 2045 lets the encoded text carry line breaks. A Base64 keeps them as the document wrote them, and Base64.Canonical removes them.
func (Base64) Bytes ¶
Bytes returns the bytes the text stands for.
The bytes are decoded here, not when the document is read, so a caller that only passes the value on never pays for the decode. Bytes returns an error when the text is not RFC 2045 base64. A decoded "!!binary" is always valid, so the error can only come from a Base64 the caller built.
func (Base64) Canonical ¶
Canonical returns the text without the line breaks and spaces that RFC 2045 allows inside the encoded text. It applies token.CanonicalBase64, which the parser also uses to name a "!!binary" key.
func (Base64) MarshalJSON ¶
MarshalJSON writes the base64 text as a JSON string, in canonical form.
JSON has no binary type and no tags, so a Base64 is written as its text, as ToJSON writes the "!!binary" it came from and as encoding/json writes a []byte. The line breaks are removed, so the value comes back on one line.
func (Base64) String ¶
String returns the base64 text.
It returns the encoded form, not the bytes, because fmt calls String wherever the value is logged, and the raw payload may not be printable. Use Base64.Bytes for the payload.
func (*Base64) UnmarshalJSON ¶
UnmarshalJSON reads a JSON string as base64 text.
UnmarshalJSON checks the text but does not decode it, because a Base64 holds the encoded form and Base64.Bytes decodes it. A string that is not RFC 2045 base64 returns an error here, so the first call to Bytes cannot fail.
type Comment ¶
type Comment struct {
// Texts is one line of comment per entry, written without the '#'.
Texts []string
// Position places the comment relative to its value.
Position CommentPosition
}
Comment holds the text of a comment and its place relative to its value, outside any document.
Texts holds what an ast.CommentGroupNode holds, one line of text per entry, and Position adds the CommentPosition that the tree does not record. Build one with HeadComment, LineComment or FootComment, so that the texts and the position agree.
A Comment does not address a value. A CommentMap files each Comment under the path of its value.
func FootComment ¶
FootComment returns a comment to write below its value, one line per text.
func HeadComment ¶
HeadComment returns a comment to write above its value, one line per text.
func LineComment ¶
LineComment returns a comment to write after its value, on the same line.
type CommentMap ¶
CommentMap holds the comments of a document, keyed by the path of the value each belongs to.
A key is a YAML path, such as "$.foo.bar" or "$.baz[1]". CommentToMap fills a CommentMap while decoding, with each key taken from the node's own path, and WithComment reads one while encoding. So the encoder can write back a map the decoder filled.
A value can carry several comments. A head comment and a line comment stand in different places, and are two entries under the same key.
type CommentPosition ¶
type CommentPosition int
CommentPosition gives the place of a comment relative to its value: above it, on its line, or below it.
An ast.CommentGroupNode holds the text of a run of comments, but not its place. The place follows from the node the parser attaches the group to, and the tree does not record it. A caller that reads comments out of a document, or writes them into one, uses CommentPosition to give the place.
const ( // CommentHeadPosition puts the comment on the lines above its value. CommentHeadPosition CommentPosition = CommentPosition(iota) // CommentLinePosition puts the comment on its value's line, after the value. CommentLinePosition // CommentFootPosition puts the comment on the lines below its value. CommentFootPosition )
func (CommentPosition) String ¶
func (p CommentPosition) String() string
String returns the name of the position: "Head", "Line" or "Foot".
type DecodeOption ¶
DecodeOption sets an option of a Decoder, or of a call to Unmarshal or NodeToValue.
func AllowDuplicateMapKey ¶
func AllowDuplicateMapKey() DecodeOption
AllowDuplicateMapKey accepts a document that repeats a mapping key, and keeps the last value written under it.
By default a repeated key fails the decode with github.com/go-openapi/go-yaml/errors.ErrDuplicateKey, as YAML 1.2.2 section 3.2.1.1 requires. The decoder finds the repeat when the mapping closes, so a struct, a map or an any still holds the whole mapping, with the last value and without its "<<" merges, and nothing after it in the document is decoded. Under this option a Go map and a struct field hold the last value, and a MapSlice holds it at the place the key was first written.
Two keys that YAML tells apart but that share one name, such as 1 and "1", count as a repeat for a destination keyed by name: a struct, a map[string]T, an inline map, or an any under UseStringKeys. An any and a MapSlice key their entries by value, and hold both keys with or without this option.
ToJSON and ToJSONTokens keep the first value instead, under parser.WithAllowDuplicateMapKey. They hand each token over as the parser reaches it, so the caller has the first value before the repeat is read. A document read both ways under the option can therefore give two values for one repeated key. Leave the option off where a decode and a conversion must agree.
func AllowFieldPrefixes ¶
func AllowFieldPrefixes(prefixes ...string) DecodeOption
AllowFieldPrefixes lets DisallowUnknownField accept an unknown key that starts with one of prefixes, such as "x-".
func CommentToMap ¶
func CommentToMap(cm CommentMap) DecodeOption
CommentToMap collects the comments of the document being decoded into cm.
Each comment is filed under the path of the value it belongs to, so WithComment can write the map back. cm must not be nil: the decoder fills the caller's map and does not return one.
A Go value has nowhere to hold a comment, so use CommentToMap to keep a document's comments when you decode it.
func CustomUnmarshaler ¶
func CustomUnmarshaler[T any](unmarshaler func(*T, []byte) error) DecodeOption
CustomUnmarshaler decodes every T with unmarshaler, which receives the YAML text of the node, in place of any other decoding of T. The text is the one an Unmarshaler receives.
It takes precedence over a function registered for the same type with RegisterCustomUnmarshaler.
func DisallowUnknownField ¶
func DisallowUnknownField() DecodeOption
DisallowUnknownField returns an error for a mapping key that names no exported field of the struct it decodes into. A field tagged "-" names nothing. Use AllowFieldPrefixes to let some keys through.
Under UseJSONTags, a name that two embedded structs offer at the same depth, and that neither tag settles, reaches no field. Its key is then unknown and fails the decode, as with encoding/json/v2's RejectUnknownMembers.
func RecursiveDir ¶
func RecursiveDir(isRecursive bool) DecodeOption
RecursiveDir makes ReferenceDirs read the subdirectories of its directories too.
func ReferenceDirs ¶
func ReferenceDirs(dirs ...string) DecodeOption
ReferenceDirs reads the anchors declared in the .yml and .yaml files of dirs, so that the decoded document can alias them. Use RecursiveDir to read their subdirectories too.
func ReferenceFiles ¶
func ReferenceFiles(files ...string) DecodeOption
ReferenceFiles reads the anchors declared in files, so that the decoded document can alias them.
func ReferenceReaders ¶
func ReferenceReaders(readers ...io.Reader) DecodeOption
ReferenceReaders reads the anchors declared in readers, so that the decoded document can alias them.
func ShareAliases ¶
func ShareAliases() DecodeOption
ShareAliases gives every alias of one anchor the same Go value, instead of a value of its own.
By default the aliases are independent: "first: *b" and "second: *b" give two maps, and writing through one leaves the other alone. Under ShareAliases both names hold one map, and writing through either changes both.
Use it for two reasons:
- The anchors survive a round trip through a Go value. MarshalAnchor and the ",anchor" and ",alias" struct tags find an anchor by the address of its value, so the encoder writes "*name" only where one value stands under two names. Without this option, a decoded document encoded again writes the anchored node in full at each alias. A document read into an ast tree and rendered keeps its anchors either way: this concerns the Go value only.
- An alias costs nothing. A document written to exhaust memory relies on each alias building its own value (see errors.ErrExcessiveAliasing). A shared value is built once, however many aliases name it.
Do not use it on a value the program writes to afterwards, unless you want the writes shared.
func UseInferredNames ¶
func UseInferredNames(use bool) DecodeOption
UseInferredNames names a field that no tag names after its Go name, verbatim, as encoding/json does.
Without it, such a field takes its Go name lowercased, as in go.yaml.in/yaml/v3: a field declared FieldName is written "fieldname", and a document writing "FieldName" reaches nothing. Under the option, the two swap over.
The option changes names and nothing else. UseJSONTags decides which fields a decode considers, how an anonymous embedded struct is read, and how a repeated name is resolved. The two options are independent: a struct with no tags at all needs only UseInferredNames.
func UseJSONTags ¶
func UseJSONTags(use bool) DecodeOption
UseJSONTags reads a struct's fields the way encoding/json does wherever the `yaml` tag leaves off: the `json` tag names a field carrying no `yaml` tag, and an anonymous embedded struct that no tag names has its fields promoted into the outer one.
The `yaml` tag always wins, so the option adds a way to name a field and takes none away. A field carrying both tags reads the same with or without the option, and `yaml:"-"` still hides a field that the `json` tag names.
Without the option, the decoder reads the `yaml` tag alone, as go.yaml.in/yaml/v3 does, and promotes an embedded struct only where a tag says `,inline`. A type tagged for JSON alone then takes the lowercased Go name for every field, and promotes nothing, because encoding/json needs no inline marker. github.com/go-openapi/spec is such a type: without this option, decoding an OpenAPI document into spec.Swagger fills the outer map and leaves every specification in it zero.
The option does not make the decoder call UnmarshalJSON: UseJSONUnmarshaler does that, after converting the document to JSON. UseJSONTags fills the fields directly, so a type whose UnmarshalJSON does more than assign them misses that work. spec.Swagger, for one, gathers its "x-" keys into its extensions.
ToJSON reads no Go type at all, so no tag option applies to it. To decode a document into a type through its UnmarshalJSON, convert it with ToJSON and pass the result to encoding/json.
A mapping key matches a field name exactly or matches nothing, in every mode, as in go.yaml.in/yaml/v3 and encoding/json/v2. encoding/json's v1 also accepted a key that differs from a name only in case; this codec does not.
The `json` tag's `,string` option reads a number from a string, as encoding/json/v2 does: `n: "12"` fills an int and `n: 12` is rejected. It applies to a number or a pointer to one, and fails the decode of any other field.
A field that neither tag names keeps its lowercased Go name. UseInferredNames changes that name.
WriteJSONTags does the same for the encoder. Pass both, and a value read from a document is written back under the names it was read from.
Example ¶
package main
import (
"fmt"
"log"
"github.com/go-openapi/go-yaml/codec"
)
func main() {
const src = "foo: 1\nbar: c\n"
var v struct {
A int `json:"foo"`
B string `json:"bar"`
}
if err := codec.Unmarshal([]byte(src), &v, codec.UseJSONTags(true)); err != nil {
log.Fatal(err)
}
fmt.Println(v.A)
fmt.Println(v.B)
}
Output: 1 c
func UseJSONUnmarshaler ¶
func UseJSONUnmarshaler() DecodeOption
UseJSONUnmarshaler decodes a type that implements encoding/json.Unmarshaler, and none of this package's unmarshaler interfaces, by converting its node to JSON and calling UnmarshalJSON.
func UseOrderedMap ¶
func UseOrderedMap() DecodeOption
UseOrderedMap decodes a mapping into a MapSlice wherever the destination does not name a type, as for an any, so that the mapping keeps the order of its keys.
func UseStringKeys ¶
func UseStringKeys() DecodeOption
UseStringKeys reads every mapping key as text, so a map with an interface key type holds strings instead of the Go types the keys resolve to.
Without it, "1.5: a" decoded into a map[any]any gives the key float64(1.5), "true: a" gives bool(true), and a key the map's own type cannot hold is an error. With it both keys are strings, spelled as a map[string]any spells them, as a JSON object needs. A map whose key type is named, such as a map[float64]any, is left alone, because the caller asked for that type.
It applies to a MapSlice too, whose MapItem.Key otherwise holds the resolved key. There "1: a" and "\"1\": b" become two entries under one name, because a MapSlice can hold both.
It does not make a collection usable as a key. Go cannot hash a slice or a map, so "? [a]" is an error either way. Use parser.WithJSONCompatible to reject such keys when the document is parsed.
func Validator ¶
func Validator(validate func(any) error) DecodeOption
Validator calls validate with each struct the decoder fills, once it is filled, passing the struct by value. An error validate returns comes back as github.com/go-openapi/go-yaml/errors.ErrValidation, with a position and validate's message. errors.Is and errors.As reach validate's own error through it.
An error that is a slice whose elements have a StructField() string method points at the value of the first field it names, or at the field's key when the value is a mapping or a sequence. When the document leaves that field out, the error points at the key of the entry that writes the struct, or at the struct's first key. Any other error points at the struct's mapping. github.com/go-playground/validator/v10 returns such errors, so pass its Struct method:
validate := validator.New() dec := codec.NewDecoder(r, codec.Validator(validate.Struct))
func WithParserOptions ¶
func WithParserOptions(opts ...parser.Option) DecodeOption
WithParserOptions passes options straight to the parser the decode runs.
The decoder already turns some decode options into parser options: AllowDuplicateMapKey sets parser.WithAllowDuplicateMapKey, and CommentToMap sets parser.WithComments. Use WithParserOptions for the rest of the parser's options.
Most callers want the YAML version a document is read under:
codec.Unmarshal(src, &v, codec.WithParserOptions(parser.WithYAMLVersion(parser.YAML11)))
Without it, only a "%YAML 1.1" directive selects the 1.1 schema, and a document without one is read as YAML 1.2.
The options apply after the ones the decoder sets, in the order given, so where two options set the same thing the later one wins. Each parser option the decoder sets only turns a feature on, and no parser option turns one off, so WithParserOptions can add to them but cannot undo them.
type Decoder ¶
type Decoder struct {
// contains filtered or unexported fields
}
Decoder reads the documents of a YAML stream into Go values, one document for each call to Decoder.Decode.
func NewDecoder ¶
func NewDecoder(r io.Reader, opts ...DecodeOption) *Decoder
NewDecoder returns a decoder that reads the stream from r, with the given options.
func (*Decoder) Decode ¶
Decode reads the next document of the stream into the value v points to, and returns io.EOF once the stream holds no more document.
A value that does not fit its field leaves that field alone, and Decode reads the rest of the document, then returns the first such error. An error that stops one document, such as a repeated key, fails that call only: the next call reads the next document. A syntax error, or a document nested past the depth limit, stops the stream, and every later call returns it.
See Unmarshal for how a document maps to a Go value.
Example (DisallowUnknownField) ¶
package main
import (
"fmt"
"strings"
"github.com/go-openapi/go-yaml/codec"
)
func main() {
var v struct {
A string `yaml:"simple"`
C string `yaml:"complicated"`
}
const src = `---
simple: string
unknown: string
`
err := codec.NewDecoder(strings.NewReader(src), codec.DisallowUnknownField()).Decode(&v)
fmt.Printf("%v\n", err)
}
Output: [3:1] unknown field "unknown" 1 | --- 2 | simple: string > 3 | unknown: string ^
type EncodeOption ¶
EncodeOption sets an option of an Encoder, or of a call to Marshal or ValueToNode.
func AutoInt ¶
func AutoInt() EncodeOption
AutoInt writes a float with no fractional part as an integer: 1.0 is written 1.
func CustomMarshaler ¶
func CustomMarshaler[T any](marshaler func(T) ([]byte, error)) EncodeOption
CustomMarshaler encodes every T with marshaler, which returns the YAML text to write, in place of any other encoding of T.
Where T implements MarshalYAML on a pointer receiver, give *T as the type parameter. The option takes precedence over a function registered for the same type with RegisterCustomMarshaler.
func Flow ¶
func Flow(isFlowStyle bool) EncodeOption
Flow writes every mapping and sequence in flow style: {k: v} and [a, b].
func Indent ¶
func Indent(spaces int) EncodeOption
Indent sets the number of spaces of each indentation level. The default is DefaultIndentSpaces.
func IndentSequence ¶
func IndentSequence(indent bool) EncodeOption
IndentSequence indents a block sequence under a mapping key by one level, as set by Indent. By default the "- " of each entry stands in the key's column.
func JSON ¶
func JSON() EncodeOption
JSON writes the document in flow style with every string quoted, so that the output is also JSON.
func MarshalAnchor ¶
func MarshalAnchor(callback func(*ast.AnchorNode, any) error) EncodeOption
MarshalAnchor calls callback for each anchor the encoder writes, with the anchor node and the value it anchors.
The encoder finds an anchor by the address of its value. A decoded document encoded again therefore keeps its anchors only where the decode gave every name of an anchor one value. Pass ShareAliases to Unmarshal for that. Without it, each alias has a value of its own, and the anchored node is written in full at every alias.
func OmitEmpty ¶
func OmitEmpty() EncodeOption
OmitEmpty skips every struct field that encoding/json v1's omitempty would skip: a false bool, a zero number, an empty string, a nil pointer or interface, and an empty slice or map.
It applies to every field, tagged or not. This package's omitempty tag also skips a value whose IsZero method returns true, and a struct whose fields would all be skipped (see Marshal).
Under WriteJSONTags, a field with a `json` tag follows encoding/json/v2's omitempty instead, as its own `,omitempty` flag does: it is skipped when it encodes as null, an empty string, an empty mapping or an empty sequence, and a false bool or a zero number is written.
func OmitZero ¶
func OmitZero() EncodeOption
OmitZero skips every struct field that the omitzero tag would skip, as if each field carried it. See Marshal for the rule.
func SkipDuplicateMapKey ¶
func SkipDuplicateMapKey() EncodeOption
SkipDuplicateMapKey writes the first of two map keys that YAML reads as one key, and drops the rest.
A Go map can hold two keys that YAML reads as one: int(1) and uint64(1) in a map[any]any, two NaN in a map[float64]T, or one instant in two zones in a map[time.Time]T. Without this option, the encoder returns an error wrapping errors.ErrDuplicateKey for such a map, as the decoder does for a document that writes one key twice.
The encoder orders a map's keys by their text and then by their Go type, so the same key comes first whatever order the map iterates in. AllowDuplicateMapKey keeps the last value on decoding instead: the decoder has every entry before it fills a map, while the encoder writes each key as it comes to it.
func UseJSONMarshaler ¶
func UseJSONMarshaler() EncodeOption
UseJSONMarshaler encodes a type that implements encoding/json.Marshaler, and neither this package's marshaler interfaces nor encoding.TextMarshaler, by calling MarshalJSON and converting the JSON it returns to YAML.
func UseLiteralStyleIfMultiline ¶
func UseLiteralStyleIfMultiline(useLiteralStyleIfMultiline bool) EncodeOption
UseLiteralStyleIfMultiline writes a string that spans several lines as a literal block scalar ("|").
Two kinds of string stay double-quoted, because the encoder has no block scalar that reads back as the same string. A string holding a carriage return or a byte order mark is one: a reader turns "\r\n" into "\n". A string whose first line of text starts with a space is the other: a reader takes the block's indentation from that line, and the encoder writes no indentation indicator.
func UseSingleQuote ¶
func UseSingleQuote(sq bool) EncodeOption
UseSingleQuote quotes a string that needs quoting with single quotes. A string holding a character that only an escape can write is still double-quoted.
func WithComment ¶
func WithComment(cm CommentMap) EncodeOption
WithComment writes the comments cm holds into the document being encoded.
Each key is parsed as a YAML path, and the comment is written at the value the path addresses. A key that addresses no value in the document is skipped without an error, so a map read from one document can be written to another that lacks some of its values.
The keys are full path expressions, so "$..a" and "$[*]" parse. A comment goes in one place, so only the first value such a key reaches takes the comment. Prefer keys that address one value each.
func WithSmartAnchor ¶
func WithSmartAnchor() EncodeOption
WithSmartAnchor writes an anchor on the first map value that a pointer reaches, and an alias at every later value with the same pointer. The anchor takes the name of the map key, with a suffix where two keys share a name. The option is experimental, and cannot be combined with the anchor and alias struct tags.
A value decoded by Unmarshal shares a pointer only where the decode gave two names one value, so pass ShareAliases to the decode. Without it, every alias has a value of its own and the option finds no pointer to share.
func WriteInferredNames ¶
func WriteInferredNames(write bool) EncodeOption
WriteInferredNames writes a field that no tag names under its Go name, verbatim, the way encoding/json writes it, and mirrors UseInferredNames on the decoder.
Without it such a field is written under its lowercased Go name, which is what go.yaml.in/yaml/v3 writes.
func WriteJSONTags ¶
func WriteJSONTags(write bool) EncodeOption
WriteJSONTags names a struct's fields the way encoding/json names them wherever the `yaml` tag leaves off, so that a value read under UseJSONTags is written back under the names it was read from.
The `json` tag names a field that carries no `yaml` tag, and an anonymous embedded struct that no tag names has its fields written into the mapping around it, not under a key of its own. The `yaml` tag still wins wherever a field carries one.
The `json` tag's flags follow encoding/json/v2. `,string` writes a number as a string, such as `n: "12"`. `,omitempty` drops a field that encodes as null, an empty string, an empty mapping or an empty sequence, and keeps false and 0. `yaml:",omitempty"` keeps the rule of go.yaml.in/yaml/v3, which drops false and 0 too.
Without it the encoder writes the `yaml` tag's name, or the lowercased Go name, as go.yaml.in/yaml/v3 does.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder writes Go values to a YAML stream, one document for each call to Encoder.Encode.
func NewEncoder ¶
func NewEncoder(w io.Writer, opts ...EncodeOption) *Encoder
NewEncoder returns an encoder that writes to w, with the given options. Each call to Encoder.Encode writes a whole document to w, so there is nothing to flush.
func (*Encoder) Encode ¶
Encode writes v to the stream as one document. Every document after the first opens with a "---" separator.
See Marshal for how a Go value maps to YAML.
Encode writes the document as it walks v, through an ast.Stream, and keeps only the output in memory. It builds the whole tree first under WithComment, WithSmartAnchor, MarshalAnchor, Flow and JSON. Either way an error writes nothing to the stream.
func (*Encoder) EncodeToNode ¶
EncodeToNode returns the AST node that Encoder.Encode would write for v, without writing it.
type GoYAMLMarshaler ¶
GoYAMLMarshaler returns another Go value to encode in place of this one.
It has the shape github.com/go-yaml/yaml expects. Prefer Marshaler, which returns the text, so the encoder makes no second pass over a returned value.
type GoYAMLUnmarshaler ¶
GoYAMLUnmarshaler receives a function that decodes its value into any destination.
It has the shape github.com/go-yaml/yaml expects. Prefer Unmarshaler, which receives the text directly.
type IsZeroer ¶
type IsZeroer interface {
IsZero() bool
}
IsZeroer reports whether a value is zero. The encoder skips a field whose IsZero method returns true under the omitempty and omitzero tags, and under the OmitZero option. time.Time implements it.
type JSONToken ¶
type JSONToken struct {
// Value is the text of a key, a string or a number, and empty otherwise.
Value string
// At gives the position of the token's first byte in the source. Offset is a
// 0-based byte index, so src[At.Offset():] begins at the token, and Line
// and Column count from 1 with Column counting characters.
//
// A block collection writes no "}" or "]", so its closer takes the position just past the last byte the
// collection encloses.
At token.Position
// Kind gives the kind of the token.
Kind JSONTokenKind
// Bool is the value of a [JSONBool].
Bool bool
}
JSONToken is one token of the JSON that holds the same values as a YAML document.
Value holds the text of a key, a string or a number, and is empty for the other kinds. A number keeps its digits instead of a parsed float, so a value that JSON can carry whole is not rounded. Bool holds true or false, and counts only when Kind is JSONBool.
A token's Value stays valid as long as the source does: the scanner returns either a window into the document or a string of its own, never a view of a buffer it reuses. The nodes of a walk, by contrast, are valid only until Leave returns.
No token stands for a "," or a ":". An object is a JSONObjectStart, its members as a JSONKey and a value each, then a JSONObjectEnd.
type JSONTokenKind ¶
type JSONTokenKind uint8
JSONTokenKind gives the kind of a JSONToken.
A JSON document is made of nine kinds of token once its separators are left out. They are enough for a reader that colors by kind, indexes by key or records positions. No YAML feature reaches the tokens: no tags, anchors, styles or comments.
const ( // JSONInvalid is the zero value. No token handed over has this kind. JSONInvalid JSONTokenKind = iota // JSONObjectStart opens a mapping: "{". JSONObjectStart // JSONObjectEnd closes a mapping: "}". JSONObjectEnd // JSONArrayStart opens a sequence: "[". JSONArrayStart // JSONArrayEnd closes a sequence: "]". JSONArrayEnd // JSONKey holds a mapping key, as the string that names a JSON member. JSONKey // JSONString holds a string value, decoded. JSONString // JSONNumber holds a number value, as the digits JSON writes it with. JSONNumber // JSONBool holds true or false, in [JSONToken.Bool]. JSONBool // JSONNull stands for null. JSONNull )
func (JSONTokenKind) String ¶
func (k JSONTokenKind) String() string
String returns the bracket a collection token writes, such as "{", or the name of any other kind, such as "key" or "number". It returns "invalid" for JSONInvalid.
type JSONTokens ¶
type JSONTokens struct {
// contains filtered or unexported fields
}
JSONTokens converts a YAML document to JSON tokens, and tracks the position of the conversion while it reads.
Build one with ToJSONTokens and range over JSONTokens.Tokens. JSONTokens.Depth and JSONTokens.Path describe the token the range is on, and JSONTokens.Err returns the error that stopped it.
func ToJSONTokens ¶
func ToJSONTokens(src []byte, opts ...parser.Option) *JSONTokens
ToJSONTokens returns a reader of src as JSON tokens, which hands each token over as the parser reaches it.
The tokens hold what ToJSON writes, and the two reject the same documents. A value JSON cannot write, such as an infinity, a NaN or a collection used as a mapping key, stops the conversion with an error.
For a stream of several documents, only the first document's tokens are handed over, as Unmarshal decodes the first. The others are still converted, and an error in one of them stops the range, as it does for ToJSON.
opts go to the parser. parser.WithJSONCompatible is always on.
A document that repeats a mapping key returns an error, as it does for Unmarshal. Under parser.WithAllowDuplicateMapKey, the conversion keeps the first entry and drops the later one, while a decoder under AllowDuplicateMapKey keeps the last value. The conversion hands the first entry's tokens over before it reads the repeat, so it cannot keep the last one.
ToJSONTokens reads nothing until the caller ranges over JSONTokens.Tokens, and each range converts the document again.
func (*JSONTokens) AppendPath ¶
func (s *JSONTokens) AppendPath(dst []byte) []byte
AppendPath appends JSONTokens.Path to dst and returns the result, so that a caller can reuse one buffer.
func (*JSONTokens) Budget ¶
func (s *JSONTokens) Budget(tokens int) *JSONTokens
Budget caps the number of tokens one document may hand over, and returns the receiver so that the call fits in the range statement.
Each alias hands over everything its anchor names again, so a document of a few hundred bytes can name more values than memory holds. The depth limit and the size of a scalar do not bound that, and Budget does. Set it for input you did not write.
The token past the budget stops the conversion with an error matching github.com/go-openapi/go-yaml/errors.ErrNotJSON, at that token's position. The decoder bounds aliases differently, with ErrExcessiveAliasing, and the two do not match.
A budget of 0, which is the default, does not bound it.
func (*JSONTokens) Depth ¶
func (s *JSONTokens) Depth() int
Depth counts the objects and arrays open around the token just handed over.
An opening JSONObjectStart or JSONArrayStart counts the collection it opens. A root scalar is at depth 0. A root object's opener, its keys and its values are at 1, and a collection nested in it is at 2 from its opener on.
A closing JSONObjectEnd or JSONArrayEnd has the depth it returns to, not the depth it closes, so the opener and the closer of one collection have different depths.
func (*JSONTokens) Err ¶
func (s *JSONTokens) Err() error
Err returns the error that stopped the conversion, or nil.
A range over JSONTokens.Tokens ends without a sign on an error, as a lexer does, so call Err after the loop.
func (*JSONTokens) OneDocument ¶
func (s *JSONTokens) OneDocument() *JSONTokens
OneDocument makes a stream of more than one document an error, and returns the receiver so that the call fits in the range statement.
Without it, the conversion hands over the first document of a stream, as Unmarshal decodes the first, and reads the others without handing them over. Use OneDocument when you build one JSON value, so that a second document is an error and not silently dropped.
A "%YAML" or "%TAG" line does not count as a document of its own.
func (*JSONTokens) Path ¶
func (s *JSONTokens) Path() string
Path returns the RFC 6901 JSON pointer to the token just handed over.
A key and its value share one pointer, the pointer of the member. The document's outermost value has the pointer "". Path builds the pointer from the open collections when it is called, so the conversion keeps no pointer between calls.
func (*JSONTokens) Tokens ¶
func (s *JSONTokens) Tokens() iter.Seq[JSONToken]
Tokens iterates the tokens of the first document, in the order JSON writes them, and stops at the first error.
Breaking out of the range stops the parse. JSONTokens.Depth and JSONTokens.Path describe the token the loop body is running on, so call them inside the loop.
type MapItem ¶
type MapItem struct {
Key, Value any
}
MapItem is one entry of a MapSlice or a MapSliceSeq.
A decode fills Key with the value the key resolves to, as it fills a map[any]any key: "1:" gives uint64(1), "1.0:" gives float64(1), "null:" gives nil and "true:" gives true. So the string "1.0" and the float 1.0 are two entries, as YAML 1.2.2 section 3.2.1.1 requires. Use UseStringKeys to read every key as text instead.
A key must be comparable. Go hashes no slice, map or function, so a decode returns an error for a collection written as a mapping key, as it does for every other destination.
type MapSlice ¶
type MapSlice struct {
// contains filtered or unexported fields
}
MapSlice decodes and encodes as a YAML mapping, and keeps the order of its entries and keys that a Go map cannot tell apart.
It holds both entries of "1: a" and "\"1\": b". A map[string]any rejects the pair as a duplicate, and a map[any]any keeps both but loses the order.
Every key is unique and comparable. MapSlice.Set overwrites the entry that already holds a key, and returns an error for a key Go cannot hash. The zero value is an empty map ready for Set. Use NewMapSlice to build one from entries you already have.
Use UseOrderedMap to read every mapping of a document into one.
func NewMapSlice ¶
NewMapSlice returns a MapSlice holding items, in the order given.
It returns an error for a key Go cannot hash, and for a key given twice: two items with one key are a mistake here, while MapSlice.Set replaces the value on purpose.
func (MapSlice) At ¶
At returns the entry standing at position i, counting from 0.
It panics where a slice index panics. Range over MapSlice.All unless you need the position.
func (*MapSlice) Delete ¶
Delete removes the entry stored under key and reports whether it held one. The entries after it move up.
func (MapSlice) Get ¶
Get returns the value stored under key, and whether the map holds one.
A key Go cannot hash addresses no entry: Get reports it absent, and does not panic.
func (MapSlice) MarshalJSON ¶
MarshalJSON writes the entries as a JSON object, in entry order.
JSON gives an object no order, so a reader that loads the object into a map loses it. The bytes keep it, for a reader that reads them in order or compares them. A MapSliceSeq writes the same object, because JSON cannot write the "!!omap" tag.
The encoder names the keys as Marshal with JSON does, so a MapSlice writes the same JSON as ToJSON writes for the document it was read from.
func (*MapSlice) Set ¶
Set stores value under key.
Where the map already holds the key, the entry keeps its position and takes the new value. Otherwise the entry goes at the end. Set returns an error for a key Go cannot hash.
func (MapSlice) ToMap ¶
ToMap returns the entries as a Go map, dropping the order.
Every key is comparable, so the map holds as many entries as the MapSlice.
func (*MapSlice) UnmarshalJSON ¶
UnmarshalJSON reads a JSON object, keeping the order its members were written in.
encoding/json reads an object into a map and loses the order, so UnmarshalJSON reads the token stream instead. A nested object becomes a MapSlice too, so the order is kept at every depth, and an array becomes a []any.
A number resolves as the YAML decoder resolves it, to a uint64, an int64 or a float64, where encoding/json gives a float64 for every number. A value read here and written back as YAML keeps the type the YAML decoder gives it.
type MapSliceSeq ¶
type MapSliceSeq MapSlice
MapSliceSeq is a MapSlice that reads and writes YAML's "!!omap", a sequence of one-entry mappings: "!!omap [{x: 1}, {y: 2}]".
It holds the same entries under the same rules. The encoder writes a MapSlice as a plain mapping, and a MapSliceSeq as the tagged sequence, with or without UseOrderedMap. A decode into an any builds a MapSliceSeq for a node tagged "!!omap", and a decode into a named destination builds the type it names.
The two convert into each other: MapSlice(seq) and MapSliceSeq(m).
func NewMapSliceSeq ¶
func NewMapSliceSeq(items ...MapItem) (MapSliceSeq, error)
NewMapSliceSeq returns a MapSliceSeq holding items, with the checks of NewMapSlice.
func (MapSliceSeq) All ¶
func (s MapSliceSeq) All() iter.Seq2[any, any]
All iterates the entries in order.
func (MapSliceSeq) At ¶
func (s MapSliceSeq) At(i int) MapItem
At returns the entry standing at position i, counting from 0.
func (*MapSliceSeq) Delete ¶
func (s *MapSliceSeq) Delete(key any) bool
Delete removes the entry stored under key and reports whether it held one.
func (MapSliceSeq) Get ¶
func (s MapSliceSeq) Get(key any) (any, bool)
Get returns the value stored under key, and whether the map holds one.
func (MapSliceSeq) Keys ¶
func (s MapSliceSeq) Keys() iter.Seq[any]
Keys iterates the keys in order.
func (MapSliceSeq) MarshalJSON ¶
func (s MapSliceSeq) MarshalJSON() ([]byte, error)
MarshalJSON writes the entries as a JSON object, as MapSlice.MarshalJSON does, because JSON cannot write the "!!omap" tag that tells the two types apart.
func (*MapSliceSeq) Set ¶
func (s *MapSliceSeq) Set(key, value any) error
Set stores value under key, as MapSlice.Set does.
func (MapSliceSeq) ToMap ¶
func (s MapSliceSeq) ToMap() map[any]any
ToMap returns the entries as a Go map, dropping the order.
func (*MapSliceSeq) UnmarshalJSON ¶
func (s *MapSliceSeq) UnmarshalJSON(b []byte) error
UnmarshalJSON reads a JSON object, as MapSlice.UnmarshalJSON does.
type NodeUnmarshaler ¶
NodeUnmarshaler receives the node its value was read from.
type RawMessage ¶
type RawMessage []byte
RawMessage holds an encoded YAML value as it stands, as encoding/json.RawMessage does for JSON.
Use it to delay the decoding of part of a document, or to write YAML text that is already encoded. It implements Marshaler and Unmarshaler, and also encoding/json.Marshaler and encoding/json.Unmarshaler.
func (RawMessage) MarshalJSON ¶
func (m RawMessage) MarshalJSON() ([]byte, error)
MarshalJSON converts the encoded YAML value to JSON.
func (RawMessage) MarshalYAML ¶
func (m RawMessage) MarshalYAML() ([]byte, error)
MarshalYAML returns the encoded value, or "null" for a nil RawMessage.
func (*RawMessage) UnmarshalJSON ¶
func (m *RawMessage) UnmarshalJSON(b []byte) error
UnmarshalJSON stores a copy of a JSON value, which is also YAML.
func (*RawMessage) UnmarshalYAML ¶
func (m *RawMessage) UnmarshalYAML(dt []byte) error
UnmarshalYAML stores a copy of the encoded value.
type Unmarshaler ¶
Unmarshaler receives the YAML text of its value.
The decoder renders data from the parsed node, so data never aliases the source document. Each call receives a new slice, which UnmarshalYAML may keep without copying it.
The text parses back as the same value, with the renderer's layout: a nested value starts at column 0, so a sequence indented four spaces under its key passes as "- 1\n- 2". Data also differs from the source in these ways:
- an alias is written out as the value its anchor names;
- comments are dropped, unless the decoder was given CommentToMap;
- under YAML 1.1, data starts with "%YAML 1.1\n---\n", so it parses under the same version.
Tags and quoting are kept: "h: !!str 3" passes "!!str 3".
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
astutils
Package astutils holds the codec's helpers that read or edit an ast tree.
|
Package astutils holds the codec's helpers that read or edit an ast tree. |
|
codecutils
Package codecutils holds the codec's helpers that read and convert Go values.
|
Package codecutils holds the codec's helpers that read and convert Go values. |
|
structfields
Package structfields reads the fields a Go struct type shows to the codec: the name each is written under, its `yaml` flags, and the fields an embedded or `,inline` struct promotes.
|
Package structfields reads the fields a Go struct type shows to the codec: the name each is written under, its `yaml` flags, and the fields an embedded or `,inline` struct promotes. |