go-yaml: github.com/goccy/go-yaml Index | Examples | Files | Directories

package yaml

import "github.com/goccy/go-yaml"

Index

Examples

Package Files

decode.go encode.go option.go path.go struct.go validate.go yaml.go

Constants

const (
    // DefaultIndentSpaces default number of space for indent
    DefaultIndentSpaces = 2
)
const (
    // StructTagName tag keyword for Marshal/Unmarshal
    StructTagName = "yaml"
)

Variables

var (
    ErrInvalidQuery      = xerrors.New("invalid query")
    ErrInvalidPath       = xerrors.New("invalid path instance")
    ErrInvalidPathString = xerrors.New("invalid path string")
)

func FormatError Uses

func FormatError(e error, colored, inclSource bool) string

FormatError is a utility function that takes advantage of the metadata stored in the errors returned by this package's parser.

If the second argument `colored` is true, the error message is colorized. If the third argument `inclSource` is true, the error message will contain snippets of the YAML source that was used.

func Marshal Uses

func Marshal(v interface{}) ([]byte, error)

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 included if that method 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.

anchor       Marshal with anchor. If want to define anchor name explicitly, use anchor=name style.
             Otherwise, if used 'anchor' name only, used the field name lowercased as the anchor name

alias        Marshal with alias. If want to define alias name explicitly, use alias=name style.
             Otherwise, If omitted alias name and the field type is pointer type,
             assigned anchor name automatically from same pointer address.

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"

func MarshalWithOptions Uses

func MarshalWithOptions(v interface{}, opts ...EncodeOption) ([]byte, error)

MarshalWithOptions serializes the value provided into a YAML document with EncodeOptions.

func Unmarshal Uses

func Unmarshal(data []byte, v interface{}) error

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

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.

func UnmarshalWithOptions Uses

func UnmarshalWithOptions(data []byte, v interface{}, opts ...DecodeOption) error

UnmarshalWithOptions decodes with DecodeOptions the first document found within the in byte slice and assigns decoded values into the out value.

func ValueToNode Uses

func ValueToNode(v interface{}, opts ...EncodeOption) (ast.Node, error)

ValueToNode convert from value to ast.Node.

type BytesMarshaler Uses

type BytesMarshaler interface {
    MarshalYAML() ([]byte, error)
}

BytesMarshaler 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.

type BytesUnmarshaler Uses

type BytesUnmarshaler interface {
    UnmarshalYAML([]byte) error
}

BytesUnmarshaler interface may be implemented by types to customize their behavior when being unmarshaled from a YAML document.

type DecodeOption Uses

type DecodeOption func(d *Decoder) error

DecodeOption functional option type for Decoder

func DisallowDuplicateKey Uses

func DisallowDuplicateKey() DecodeOption

DisallowDuplicateKey causes an error when mapping keys that are duplicates

func DisallowUnknownField Uses

func DisallowUnknownField() DecodeOption

DisallowUnknownField causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.

func RecursiveDir Uses

func RecursiveDir(isRecursive bool) DecodeOption

RecursiveDir search yaml file recursively from passed dirs by ReferenceDirs option

func ReferenceDirs Uses

func ReferenceDirs(dirs ...string) DecodeOption

ReferenceDirs pass to Decoder that reference to anchor defined by files under the passed dirs

func ReferenceFiles Uses

func ReferenceFiles(files ...string) DecodeOption

ReferenceFiles pass to Decoder that reference to anchor defined by passed files

func ReferenceReaders Uses

func ReferenceReaders(readers ...io.Reader) DecodeOption

ReferenceReaders pass to Decoder that reference to anchor defined by passed readers

func Strict Uses

func Strict() DecodeOption

Strict enable DisallowUnknownField and DisallowDuplicateKey

func UseOrderedMap Uses

func UseOrderedMap() DecodeOption

UseOrderedMap can be interpreted as a map, and uses MapSlice ( ordered map ) aggressively if there is no type specification

func Validator Uses

func Validator(v StructValidator) DecodeOption

Validator set StructValidator instance to Decoder

type Decoder Uses

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

Decoder reads and decodes YAML values from an input stream.

func NewDecoder Uses

func NewDecoder(r io.Reader, opts ...DecodeOption) *Decoder

NewDecoder returns a new decoder that reads from r.

func (*Decoder) Decode Uses

func (d *Decoder) Decode(v interface{}) error

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.

type EncodeOption Uses

type EncodeOption func(e *Encoder) error

EncodeOption functional option type for Encoder

func Flow Uses

func Flow(isFlowStyle bool) EncodeOption

Flow encoding by flow style

func Indent Uses

func Indent(spaces int) EncodeOption

Indent change indent number

func JSON Uses

func JSON() EncodeOption

JSON encode in JSON format

func MarshalAnchor Uses

func MarshalAnchor(callback func(*ast.AnchorNode, interface{}) error) EncodeOption

MarshalAnchor call back if encoder find an anchor during encoding

type Encoder Uses

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

Encoder writes YAML values to an output stream.

func NewEncoder Uses

func NewEncoder(w io.Writer, opts ...EncodeOption) *Encoder

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

func (*Encoder) Close Uses

func (e *Encoder) Close() error

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

func (*Encoder) Encode Uses

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

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.

func (*Encoder) EncodeToNode Uses

func (e *Encoder) EncodeToNode(v interface{}) (ast.Node, error)

EncodeToNode convert v to ast.Node.

type FieldError Uses

type FieldError interface {
    StructField() string
}

FieldError need to implement StructField method only ( see https://godoc.org/gopkg.in/go-playground/validator.v9#FieldError )

type InterfaceMarshaler Uses

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

InterfaceMarshaler interface has MarshalYAML compatible with github.com/go-yaml/yaml package.

type InterfaceUnmarshaler Uses

type InterfaceUnmarshaler interface {
    UnmarshalYAML(func(interface{}) error) error
}

InterfaceUnmarshaler interface has UnmarshalYAML compatible with github.com/go-yaml/yaml package.

type IsZeroer Uses

type IsZeroer interface {
    IsZero() bool
}

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.

type MapItem Uses

type MapItem struct {
    Key, Value interface{}
}

MapItem is an item in a MapSlice.

type MapSlice Uses

type MapSlice []MapItem

MapSlice encodes and decodes as a YAML map. The order of keys is preserved when encoding and decoding.

func (MapSlice) ToMap Uses

func (s MapSlice) ToMap() map[interface{}]interface{}

ToMap convert to map[interface{}]interface{}.

type Path Uses

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

Path represent YAMLPath ( like a JSONPath ).

func PathString Uses

func PathString(s string) (*Path, error)

PathString create Path from string

YAMLPath rule $ : the root object/element . : child operator .. : recursive descent [num] : object/element of array by number [*] : all objects/elements for array.

func (*Path) AnnotateSource Uses

func (p *Path) AnnotateSource(source []byte, colored bool) ([]byte, error)

AnnotateSource add annotation to passed source ( see section 5.1 in README.md ).

Code:

yml := `
a: 1
b: "hello"
`
var v struct {
    A   int
    B   string
}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
    panic(err)
}
if v.A != 2 {
    // output error with YAML source
    path, err := yaml.PathString("$.a")
    if err != nil {
        log.Fatal(err)
    }
    source, err := path.AnnotateSource([]byte(yml), false)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("a value expected 2 but actual %d:\n%s\n", v.A, string(source))
}

Output:

a value expected 2 but actual 1:
>  2 | a: 1
          ^
   3 | b: "hello"

func (*Path) Filter Uses

func (p *Path) Filter(target, v interface{}) error

Filter filter from target by YAMLPath and set it to v.

func (*Path) FilterFile Uses

func (p *Path) FilterFile(f *ast.File) (ast.Node, error)

FilterFile filter from ast.File by YAMLPath.

func (*Path) FilterNode Uses

func (p *Path) FilterNode(node ast.Node) (ast.Node, error)

FilterNode filter from node by YAMLPath.

func (*Path) MergeFromFile Uses

func (p *Path) MergeFromFile(dst *ast.File, src *ast.File) error

MergeFromFile merge ast.File into ast.File.

func (*Path) MergeFromNode Uses

func (p *Path) MergeFromNode(dst *ast.File, src ast.Node) error

MergeFromNode merge ast.Node into ast.File.

func (*Path) MergeFromReader Uses

func (p *Path) MergeFromReader(dst *ast.File, src io.Reader) error

MergeFromReader merge YAML text into ast.File.

func (*Path) Read Uses

func (p *Path) Read(r io.Reader, v interface{}) error

Read decode from r and set extracted value by YAMLPath to v.

func (*Path) ReadNode Uses

func (p *Path) ReadNode(r io.Reader) (ast.Node, error)

ReadNode create AST from r and extract node by YAMLPath.

func (*Path) ReplaceWithFile Uses

func (p *Path) ReplaceWithFile(dst *ast.File, src *ast.File) error

ReplaceWithFile replace ast.File with ast.File.

func (*Path) ReplaceWithNode Uses

func (p *Path) ReplaceWithNode(dst *ast.File, node ast.Node) error

ReplaceNode replace ast.File with ast.Node.

func (*Path) ReplaceWithReader Uses

func (p *Path) ReplaceWithReader(dst *ast.File, src io.Reader) error

ReplaceWithReader replace ast.File with io.Reader.

func (*Path) String Uses

func (p *Path) String() string

String path to text.

type PathBuilder Uses

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

PathBuilder represent builder for YAMLPath.

func (*PathBuilder) Build Uses

func (b *PathBuilder) Build() *Path

Build build YAMLPath.

func (*PathBuilder) Child Uses

func (b *PathBuilder) Child(name string) *PathBuilder

Child add '.name' to current path.

func (*PathBuilder) Index Uses

func (b *PathBuilder) Index(idx uint) *PathBuilder

Index add '[idx]' to current path.

func (*PathBuilder) IndexAll Uses

func (b *PathBuilder) IndexAll() *PathBuilder

IndexAll add '[*]' to current path.

func (*PathBuilder) Recursive Uses

func (b *PathBuilder) Recursive(selector string) *PathBuilder

Recursive add '..selector' to current path.

func (*PathBuilder) Root Uses

func (b *PathBuilder) Root() *PathBuilder

Root add '$' to current path.

type StructField Uses

type StructField struct {
    FieldName    string
    RenderName   string
    AnchorName   string
    AliasName    string
    IsAutoAnchor bool
    IsAutoAlias  bool
    IsOmitEmpty  bool
    IsFlow       bool
    IsInline     bool
}

StructField information for each the field in structure

type StructFieldMap Uses

type StructFieldMap map[string]*StructField

type StructValidator Uses

type StructValidator interface {
    Struct(interface{}) error
}

StructValidator need to implement Struct method only ( see https://godoc.org/gopkg.in/go-playground/validator.v9#Validate.Struct )

Directories

PathSynopsis
ast
internal/errors
lexer
parser
printer
scanner
token

Package yaml imports 20 packages (graph) and is imported by 20 packages. Updated 2020-07-17. Refresh now. Tools for package owners.