Movatterモバイル変換


[0]ホーム

URL:


yaml

packagemodule
v3.0.1Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 27, 2022 License:Apache-2.0, MITImports:16Imported by:29,987

Details

Repository

github.com/go-yaml/yaml

Links

README

YAML support for the Go language

Introduction

The yaml package enables Go programs to comfortably encode and decode YAMLvalues. It was developed withinCanonical aspart of thejuju project, and is based on apure Go port of the well-knownlibyamlC library to parse and generate YAML data quickly and reliably.

Compatibility

The yaml package supports most of YAML 1.2, but preserves some behaviorfrom 1.1 for backwards compatibility.

Specifically, as of v3 of the yaml package:

  • YAML 1.1 bools (yes/no, on/off) are supported as long as they are beingdecoded into a typed bool value. Otherwise they behave as a string. Booleansin YAML 1.2 aretrue/false only.
  • Octals encode and decode as0777 per YAML 1.1, rather than0o777as specified in YAML 1.2, because most parsers still use the old format.Octals in the0o777 format are supported though, so new files work.
  • Does not support base-60 floats. These are gone from YAML 1.2, and wereactually never supported by this package as it's clearly a poor choice.

and offers backwardscompatibility with YAML 1.1 in some cases.1.2, including support foranchors, tags, map merging, etc. Multi-document unmarshalling is not yetimplemented, and base-60 floats from YAML 1.1 are purposefully notsupported since they're a poor design and are gone in YAML 1.2.

Installation and usage

The import path for the package isgopkg.in/yaml.v3.

To install it, run:

go get gopkg.in/yaml.v3

API documentation

If opened in a browser, the import path itself leads to the API documentation:

API stability

The package API for yaml v3 will remain stable as described ingopkg.in.

License

The yaml package is licensed under the MIT and Apache License 2.0 licenses.Please see the LICENSE file for details.

Example

package mainimport (        "fmt"        "log"        "gopkg.in/yaml.v3")var data = `a: Easy!b:  c: 2  d: [3, 4]`// Note: struct fields must be public in order for unmarshal to// correctly populate the data.type T struct {        A string        B struct {                RenamedC int   `yaml:"c"`                D        []int `yaml:",flow"`        }}func main() {        t := T{}            err := yaml.Unmarshal([]byte(data), &t)        if err != nil {                log.Fatalf("error: %v", err)        }        fmt.Printf("--- t:\n%v\n\n", t)            d, err := yaml.Marshal(&t)        if err != nil {                log.Fatalf("error: %v", err)        }        fmt.Printf("--- t dump:\n%s\n\n", string(d))            m := make(map[interface{}]interface{})            err = yaml.Unmarshal([]byte(data), &m)        if err != nil {                log.Fatalf("error: %v", err)        }        fmt.Printf("--- m:\n%v\n\n", m)            d, err = yaml.Marshal(&m)        if err != nil {                log.Fatalf("error: %v", err)        }        fmt.Printf("--- m dump:\n%s\n\n", string(d))}

This example will generate the following output:

--- t:{Easy! {2 [3 4]}}--- t dump:a: Easy!b:  c: 2  d: [3, 4]--- m:map[a:Easy! b:map[c:2 d:[3 4]]]--- m dump:a: Easy!b:  c: 2  d:  - 3  - 4

Documentation

Overview

Package yaml implements YAML support for the Go language.

Source code and other details for the project are available at GitHub:

https://github.com/go-yaml/yaml

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

funcMarshal

func Marshal(in interface{}) (out []byte, errerror)

Marshal serializes the value provided into a YAML document. The structureof 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 casefirst letter), and are marshalled using the field name lowercased as thedefault key. Custom keys may be defined via the "yaml" name in the fieldtag: the content preceding the first comma is used as the key, and thefollowing 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"

funcUnmarshal

func Unmarshal(in []byte, out interface{}) (errerror)

Unmarshal decodes the first document found within the in byte sliceand assigns decoded values into the out value.

Maps and pointers (to a struct, string, int, etc) are accepted as outvalues. If an internal pointer within a struct is not initialized,the yaml package will initialize it if necessary for unmarshallingthe provided data. The out parameter must not be nil.

The type of the decoded values should be compatible with the respectivevalues in out. If one or more values cannot be decoded due to a typemismatches, decoding continues partially until the end of the YAMLcontent, and a *yaml.TypeError is returned with details for allmissed values.

Struct fields are only unmarshalled if they are exported (have anupper case first letter), and are unmarshalled using the field namelowercased as the default key. Custom keys may be defined via the"yaml" name in the field tag: the content preceding the first commais used as the key, and the following comma-separated options areused 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 Tyaml.Unmarshal([]byte("a: 1\nb: 2"), &t)

See the documentation of Marshal for the format of tags and a list ofsupported tag options.

Example (Embedded)
package mainimport ("fmt""log""gopkg.in/yaml.v3")// 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 belowStructA `yaml:",inline"`B       string `yaml:"b"`}var data = `a: a string from struct Ab: a string from struct B`func main() {var b StructBerr := yaml.Unmarshal([]byte(data), &b)if err != nil {log.Fatalf("cannot unmarshal data: %v", err)}fmt.Println(b.A)fmt.Println(b.B)}
Output:a string from struct Aa string from struct B

Types

typeDecoder

type Decoder struct {// contains filtered or unexported fields}

A Decoder reads and decodes YAML values from an input stream.

funcNewDecoder

func NewDecoder(rio.Reader) *Decoder

NewDecoder returns a new decoder that reads from r.

The decoder introduces its own buffering and may readdata from r beyond the YAML values requested.

func (*Decoder)Decode

func (dec *Decoder) Decode(v interface{}) (errerror)

Decode reads the next YAML-encoded value from its inputand stores it in the value pointed to by v.

See the documentation for Unmarshal for details about theconversion of YAML into a Go value.

func (*Decoder)KnownFields

func (dec *Decoder) KnownFields(enablebool)

KnownFields ensures that the keys in decoded mappings toexist as fields in the struct being decoded into.

typeEncoder

type Encoder struct {// contains filtered or unexported fields}

An Encoder writes YAML values to an output stream.

funcNewEncoder

func NewEncoder(wio.Writer) *Encoder

NewEncoder returns a new encoder that writes to w.The Encoder should be closed after use to flush all datato w.

func (*Encoder)Close

func (e *Encoder) Close() (errerror)

Close closes the encoder by writing any remaining data.It does not write a stream terminating string "...".

func (*Encoder)Encode

func (e *Encoder) Encode(v interface{}) (errerror)

Encode writes the YAML encoding of v to the stream.If multiple items are encoded to the stream, thesecond and subsequent document will be precededwith a "---" document separator, but the first will not.

See the documentation for Marshal for details about the conversion of Govalues to YAML.

func (*Encoder)SetIndent

func (e *Encoder) SetIndent(spacesint)

SetIndent changes the used indentation used when encoding.

typeIsZeroer

type IsZeroer interface {IsZero()bool}

IsZeroer is used to check whether an object is zero todetermine whether it should be omitted when marshalingwith the omitempty flag. One notable implementationis time.Time.

typeKind

type Kinduint32
const (DocumentNodeKind = 1 <<iotaSequenceNodeMappingNodeScalarNodeAliasNode)

typeMarshaler

type Marshaler interface {MarshalYAML() (interface{},error)}

The Marshaler interface may be implemented by types to customize theirbehavior when being marshaled into a YAML document. The returned valueis marshaled in place of the original value implementing Marshaler.

If an error is returned by MarshalYAML, the marshaling procedure stopsand returns with the provided error.

typeNode

type Node struct {// Kind defines whether the node is a document, a mapping, a sequence,// a scalar value, or an alias to another node. The specific data type of// scalar nodes may be obtained via the ShortTag and LongTag methods.KindKind// Style allows customizing the apperance of the node in the tree.StyleStyle// Tag holds the YAML tag defining the data type for the value.// When decoding, this field will always be set to the resolved tag,// even when it wasn't explicitly provided in the YAML content.// When encoding, if this field is unset the value type will be// implied from the node properties, and if it is set, it will only// be serialized into the representation if TaggedStyle is used or// the implicit tag diverges from the provided one.Tagstring// Value holds the unescaped and unquoted represenation of the value.Valuestring// Anchor holds the anchor name for this node, which allows aliases to point to it.Anchorstring// Alias holds the node that this alias points to. Only valid when Kind is AliasNode.Alias *Node// Content holds contained nodes for documents, mappings, and sequences.Content []*Node// HeadComment holds any comments in the lines preceding the node and// not separated by an empty line.HeadCommentstring// LineComment holds any comments at the end of the line where the node is in.LineCommentstring// FootComment holds any comments following the node and before empty lines.FootCommentstring// Line and Column hold the node position in the decoded YAML text.// These fields are not respected when encoding the node.LineintColumnint}

Node represents an element in the YAML document hierarchy. While documentsare typically encoded and decoded into higher level types, such as structsand maps, Node is an intermediate representation that allows detailedcontrol over the content being decoded or encoded.

It's worth noting that although Node offers access into details such asline numbers, colums, and comments, the content when re-encoded will nothave its original textual representation preserved. An effort is made torender the data plesantly, and to preserve comments near the data theydescribe, though.

Values that make use of the Node type interact with the yaml package in thesame way any other type would do, by encoding and decoding yaml datadirectly or indirectly into them.

For example:

var person struct {        Name    string        Address yaml.Node}err := yaml.Unmarshal(data, &person)

Or by itself:

var person Nodeerr := yaml.Unmarshal(data, &person)

func (*Node)Decode

func (n *Node) Decode(v interface{}) (errerror)

Decode decodes the node and stores its data into the value pointed to by v.

See the documentation for Unmarshal for details about theconversion of YAML into a Go value.

func (*Node)Encode

func (n *Node) Encode(v interface{}) (errerror)

Encode encodes value v and stores its representation in n.

See the documentation for Marshal for details about theconversion of Go values into YAML.

func (*Node)IsZero

func (n *Node) IsZero()bool

IsZero returns whether the node has all of its fields unset.

func (*Node)LongTag

func (n *Node) LongTag()string

LongTag returns the long form of the tag that indicates the data type forthe node. If the Tag field isn't explicitly defined, one will be computedbased on the node properties.

func (*Node)SetString

func (n *Node) SetString(sstring)

SetString is a convenience function that sets the node to a string valueand defines its style in a pleasant way depending on its content.

func (*Node)ShortTag

func (n *Node) ShortTag()string

ShortTag returns the short form of the YAML tag that indicates data type forthe node. If the Tag field isn't explicitly defined, one will be computedbased on the node properties.

typeStyle

type Styleuint32
const (TaggedStyleStyle = 1 <<iotaDoubleQuotedStyleSingleQuotedStyleLiteralStyleFoldedStyleFlowStyle)

typeTypeError

type TypeError struct {Errors []string}

A TypeError is returned by Unmarshal when one or more fields inthe YAML document cannot be properly decoded into the requestedtypes. When this error is returned, the value is stillunmarshaled partially.

func (*TypeError)Error

func (e *TypeError) Error()string

typeUnmarshaler

type Unmarshaler interface {UnmarshalYAML(value *Node)error}

The Unmarshaler interface may be implemented by types to customize theirbehavior when being unmarshaled from a YAML document.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp