Code Examples
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v2"
)
// An example showing how to unmarshal embedded
// structs from YAML.
type StructA struct {
A string `yaml:"a"`
}
type StructB struct {
// Embedded structs are not treated as embedded in YAML by default. To do that,
// add the ",inline" annotation below
StructA `yaml:",inline"`
B string `yaml:"b"`
}
var data = `
a: a string from struct A
b: a string from struct B
`
func main() {
var b StructB
err := yaml.Unmarshal([]byte(data), &b)
if err != nil {
log.Fatalf("cannot unmarshal data: %v", err)
}
fmt.Println(b.A)
fmt.Println(b.B)
}
Package-Level Type Names (total 45, in which 8 are exported)
/* sort exporteds by: | */
A Decoder reads and decodes YAML values from an input stream.
parser*parserstrictbool
Decode reads the next YAML-encoded value from its input
and stores it in the value pointed to by v.
See the documentation for Unmarshal for details about the
conversion of YAML into a Go value.
SetStrict sets whether strict decoding behaviour is enabled when
decoding items in the data (see UnmarshalStrict). By default, decoding is not strict.
func NewDecoder(r io.Reader) *Decoder
An Encoder writes YAML values to an output stream.
encoder*encoder
Close closes the encoder by writing any remaining data.
It does not write a stream terminating string "...".
Encode writes the YAML encoding of v to the stream.
If multiple items are encoded to the stream, the
second and subsequent document will be preceded
with a "---" document separator, but the first will not.
See the documentation for Marshal for details about the conversion of Go
values to YAML.
*T : io.Closer
func NewEncoder(w io.Writer) *Encoder
IsZeroer is used to check whether an object is zero to
determine whether it should be omitted when marshaling
with the omitempty flag. One notable implementation
is time.Time.
( T) IsZero() bool
gopkg.in/yaml.v3.IsZeroer(interface)
*gopkg.in/yaml.v3.Node
*github.com/fatih/structs.Field
*github.com/fatih/structs.Struct
reflect.Value
time.Time
net/http.http2PriorityFrame
net/http.http2PriorityParam
T : gopkg.in/yaml.v3.IsZeroer
MapItem is an item in a MapSlice.
Keyinterface{}Valueinterface{}
MapSlice encodes and decodes as a YAML map.
The order of keys is preserved when encoding and decoding.
The Marshaler interface may be implemented by types to customize their
behavior when being marshaled into a YAML document. The returned value
is marshaled in place of the original value implementing Marshaler.
If an error is returned by MarshalYAML, the marshaling procedure stops
and returns with the provided error.
( T) MarshalYAML() (interface{}, error)
gopkg.in/yaml.v3.Marshaler(interface)
T : gopkg.in/yaml.v3.Marshaler
A TypeError is returned by Unmarshal when one or more fields in
the YAML document cannot be properly decoded into the requested
types. When this error is returned, the value is still
unmarshaled partially.
Errors[]string(*T) Error() string
*T : error
The Unmarshaler interface may be implemented by types to customize their
behavior when being unmarshaled from a YAML document. The UnmarshalYAML
method receives a function that may be called to unmarshal the original
YAML value into a field or variable. It is safe to call the unmarshal
function parameter more than once if necessary.
( T) UnmarshalYAML(unmarshal func(interface{}) error) error
gopkg.in/yaml.v3.obsoleteUnmarshaler(interface)
T : gopkg.in/yaml.v3.obsoleteUnmarshaler
Flowbool
Id holds the unique field identifier, so we can cheaply
check for field duplicates without maintaining an extra map.
Inline holds the field index if the field is part of an inlined struct.
KeystringNumintOmitEmptybool
jsonNumber is the interface of the encoding/json.Number datatype.
Repeating the interface here avoids a dependency on encoding/json, and also
supports other libraries like jsoniter, which use a similar datatype with
the same interface. Detecting this interface is useful when dealing with
structures containing json.Number, which is a string under the hood. The
encoder should prefer the use of Int64(), Float64() and string(), in that
order, when encoding this type.
( T) Float64() (float64, error)( T) Int64() (int64, error)( T) String() string
*gopkg.in/ini.v1.Key
encoding/json.Number
github.com/json-iterator/go.Number
T : fmt.Stringer
T : context.stringer
T : os/signal.stringer
T : runtime.stringer
The document structure.
// Is the document end indicator implicit?
The start/end of the document.
The document nodes.
// Is the document start indicator implicit?
The start/end of the document.
The list of tag directives.
// The end of the tag directives list.
// The beginning of the tag directives list.
The version directive.
An element of a mapping node.
// The key of the element.
// The value of the element.
The node structure.
// The end of the node.
The mapping parameters (for yaml_MAPPING_NODE).
The scalar parameters (for yaml_SCALAR_NODE).
The sequence parameters (for YAML_SEQUENCE_NODE).
// The beginning of the node.
// The node tag.
// The node type.
The prototype of a read handler.
The read handler is called when the parser needs to read more bytes from the
source. The handler should write not more than size bytes to the buffer.
The number of written bytes should be set to the size_read variable.
[in,out] data A pointer to an application data specified by
yaml_parser_set_input().
[out] buffer The buffer to write the data from the source.
[in] size The size of the buffer.
[out] size_read The actual number of bytes read from the source.
On success, the handler should return 1. If the handler failed,
the returned value should be 0. On EOF, the handler should set the
size_read to 0 and return 1.
This structure holds information about a potential simple key.
// The position mark.
// Is a simple key possible?
// Is a simple key required?
// The number of the token.
func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool)
The prototype of a write handler.
The write handler is called when the emitter needs to flush the accumulated
characters to the output. The handler should write @a size bytes of the
@a buffer to the output.
@param[in,out] data A pointer to an application data specified by
yaml_emitter_set_output().
@param[in] buffer The buffer with bytes to be written.
@param[in] size The size of the buffer.
@returns On success, the handler should return @c 1. If the handler failed,
the returned value should be @c 0.
Package-Level Functions (total 211, in which 6 are exported)
FutureLineWrap globally disables line wrapping when encoding long strings.
This is a temporary and thus deprecated method introduced to faciliate
migration towards v3, which offers more control of line lengths on
individual encodings, and has a default matching the behavior introduced
by this function.
The default formatting of v2 was erroneously changed in v2.3.0 and reverted
in v2.4.0, at which point this function was introduced to help migration.
Marshal serializes the value provided into a YAML document. The structure
of the generated document will reflect the structure of the value itself.
Maps and pointers (to struct, string, int, etc) are accepted as the in value.
Struct fields are only marshalled if they are exported (have an upper case
first letter), and are marshalled using the field name lowercased as the
default key. Custom keys may be defined via the "yaml" name in the field
tag: the content preceding the first comma is used as the key, and the
following comma-separated options are used to tweak the marshalling process.
Conflicting names result in a runtime error.
The field tag format accepted is:
`(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`
The following flags are currently supported:
omitempty Only include the field if it's not set to the zero
value for the type or to empty slices or maps.
Zero valued structs will be omitted if all their public
fields are zero, unless they implement an IsZero
method (see the IsZeroer interface type), in which
case the field will be excluded if IsZero returns true.
flow Marshal using a flow style (useful for structs,
sequences and maps).
inline Inline the field, which must be a struct or a map,
causing all of its fields or keys to be processed as if
they were part of the outer struct. For maps, keys must
not conflict with the yaml keys of other struct fields.
In addition, if the key is "-", the field is ignored.
For example:
type T struct {
F int `yaml:"a,omitempty"`
B int
}
yaml.Marshal(&T{B: 2}) // Returns "b: 2\n"
yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n"
NewDecoder returns a new decoder that reads from r.
The decoder introduces its own buffering and may read
data from r beyond the YAML values requested.
NewEncoder returns a new encoder that writes to w.
The Encoder should be closed after use to flush all data
to w.
Unmarshal decodes the first document found within the in byte slice
and assigns decoded values into the out value.
Maps and pointers (to a struct, string, int, etc) are accepted as out
values. If an internal pointer within a struct is not initialized,
the yaml package will initialize it if necessary for unmarshalling
the provided data. The out parameter must not be nil.
The type of the decoded values should be compatible with the respective
values in out. If one or more values cannot be decoded due to a type
mismatches, decoding continues partially until the end of the YAML
content, and a *yaml.TypeError is returned with details for all
missed values.
Struct fields are only unmarshalled if they are exported (have an
upper case first letter), and are unmarshalled using the field name
lowercased as the default key. Custom keys may be defined via the
"yaml" name in the field tag: the content preceding the first comma
is used as the key, and the following comma-separated options are
used to tweak the marshalling process (see Marshal).
Conflicting names result in a runtime error.
For example:
type T struct {
F int `yaml:"a,omitempty"`
B int
}
var t T
yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)
See the documentation of Marshal for the format of tags and a list of
supported tag options.
UnmarshalStrict is like Unmarshal except that any fields that are found
in the data that do not have corresponding struct members, or mapping
keys that are duplicates, will result in
an error.
Check if the character at the specified position is a digit.
Check if the character at the specified position is a hex-digit.
Check if the character at the start of the buffer can be printed unescaped.
Check if the character at the specified position is space.
Check if the character is a line break, space, or NUL.
Check if the character at the specified position is tab.
Check if the character at the specified position is NUL.
isBase60 returns whether s is in base 60 notation as defined in YAML 1.1.
The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported
in YAML 1.2 and by this package, but these should be marshalled quoted for
the time being for compatibility with other parsers.
numLess returns whether a < b.
a and b must necessarily have the same kind.
parseTimestamp parses s as a timestamp string and
returns the timestamp and reports whether it succeeded.
Timestamp formats are defined at http://yaml.org/type/timestamp.html
Peek the next token in the token queue.
Put a character to the output buffer.
Put a line break to the output buffer.
Copy a character to a string buffer and advance pointers.
Copy a line break character to a string buffer and advance pointers.
Copy a line break character from a string into buffer.
Create DOCUMENT-END.
Create DOCUMENT-START.
Check if an anchor is valid.
Check if the event data is valid.
Check if a scalar is valid.
Check if a tag is valid.
Check if a %TAG directive is valid.
Check if a %YAML directive is valid.
Append a directive to the directives stack.
Check if the document content is an empty scalar.
Check if the next events represent an empty mapping.
Check if the next events represent an empty sequence.
Check if the next node can be expressed as a simple key.
Destroy an emitter object.
Emit an event.
Expect ALIAS.
Expect a block key node.
Expect a block value node.
Expect a block item node.
Expect the root node.
Expect DOCUMENT-END.
Expect DOCUMENT-START or STREAM-END.
Expect a flow key node.
Expect a flow value node.
Expect a flow item node.
Expect MAPPING-START.
Expect a node.
Expect SCALAR.
Expect SEQUENCE-START.
Expect STREAM-START.
Flush the output buffer.
Increase the indentation level.
Create a new emitter object.
Check if we need to accumulate more events before emitting.
We accumulate extra
- 1 event for DOCUMENT-START
- 2 events for SEQUENCE-START
- 3 events for MAPPING-START
Write an anchor.
Write a scalar.
Write a tag.
Determine an acceptable scalar style.
Set the preferred line break character.
Set the canonical output style.
Set an emitter error and return false.
Set the output encoding.
// Set the indentation increment.
Set a string output.
Set a file output.
Set if unescaped non-ASCII characters are allowed.
Parse the production:
stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
************
Parse directives.
Generate an empty scalar event.
Remove a potential simple key at the current flow level.
Push the current indentation level to the stack and set the new level
the current column is greater than the indentation level. In this case,
append or insert the specified token into the token queue.
Check if a simple key may start at the current position and add it if
needed.
Pop indentation levels from the indents stack until the current level
becomes less or equal to the column. For each indentation level, append
the BLOCK-END token.
Ensure that the buffer contains at least `length` characters.
Return true on success, false on failure.
The length is supposed to be significantly less that the buffer size.
Many bad things could happen with the parser and emitter.
Scalar styles.
Many bad things could happen with the parser and emitter.
Event types.
Node types.
Token types.
Many bad things could happen with the parser and emitter.
const yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences.
Event types.
Node types.
Event types.
Scalar styles.
const yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values.
Event types.
Token types.
Event types.
Token types.
Token types.
Token types.
const yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values.
The stream encoding.
The stream encoding.
The stream encoding.
Token types.
Token types.
Many bad things could happen with the parser and emitter.
The pages are generated with Goldsv0.3.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.