yaml

package module
v0.0.0-...-e401b2b Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2014 License: LGPL-3.0 Imports: 17 Imported by: 5

README

YAML support for the Go language

Introduction

The yaml package enables Go programs to comfortably encode and decode YAML values. It was developed within Canonical as part of the juju project, and is based on a pure Go port of the well-known libyaml C library to parse and generate YAML data quickly and reliably.

Compatibility

The yaml package supports most of YAML 1.1 and 1.2, including support for anchors, tags, map merging, etc. Multi-document unmarshalling is not yet implemented, and base-60 floats from YAML 1.1 are purposefully not supported since they're a poor design and are gone in YAML 1.2.

Installation and usage

The import path for the package is gopkg.in/yaml.v2.

To install it, run:

go get gopkg.in/yaml.v2

API documentation

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

Additional information is available in the source files, specifically yaml.go.

API stability

The package API for yaml v2 will remain stable as described in gopkg.in.

License

The yaml package is licensed under the LGPL with an exception that allows it to be linked statically. Please see the LICENSE file for details.

Example

package main

import (
        "fmt"
        "log"

        "gopkg.in/yaml.v2"
)

var data = `
a: Easy!
b:
  c: 2
  d: [3, 4]
`

type T struct {
        A string
        B struct{C int; 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

Constants

This section is empty.

Variables

This section is empty.

Functions

func Marshal

func Marshal(in interface{}) (out []byte, err 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 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. 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 when marshaling if it's
                 not set to the zero value for the type or to empty
                 slices or maps. Does not apply to zero valued structs.
				    [Marshaling]

    flow         Use a flow style when marshaling (useful for structs,
                 sequences and maps.)
				    [Marshaling]

    inline       Inline the struct it's applied to, so its fields
                 are processed (during marshaling and unmarshaling)
                 as if they were part of the outer struct.
					[Marshaling, Unmarshaling]

In addition, if the key is "-", the field is ignored.

For example:

type T struct {
    F int "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 Unmarshal

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

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)

Another flag which is supported during umarshaling, but must be used on its own, is:

    regexp       Unmarshal all encountered YAML values with keys that
                 match the regular expression into the tagged field,
                 which must be a map or a slice of a type that the
                 YAML value should be unmarshaled into.
				    [Unmarshaling]

For example:

type T struct {
    A int
    B int
    Numbers map[string]int `yaml:",regexp:num.*"`
    Phrases []string `yaml:",regexp:phr.*"`
}
var t T
yaml.Unmarshal([]byte("a: 1\nb: 2\nnum1: 1\nnum2: 50\n" +
                      "phraseOne: to be or not to be\n" +
                      "phraseTwo: you can't touch my key!\n" +
                      "anotherKey: ThisValueWillNotBeUnmarshalled"), &t)

You can also use the regexp flag to get all unmapped values into a map for runtime usage:

type T struct {
    A int
    B int
    EverythingElse map[string]interface{} `yaml:",regexp:.*"`
}
var t T
yaml.Unmarshal([]byte("a: 1\nb: 2\nnum1: 1\nnum2: 50\n" +
                      "anInteger: 111\n" +
                      "aFloat: 0.5555\n" +
                      "anotherKey: WhichIsAstring\n" +
                      "aSequence: [1, 2, 3]\n" +
                      "aMapping: {hello: world}"), &t)

The resulting EverythingElse map will contain everything except the values of a and b.

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

Types

type MapItem

type MapItem struct {
	Key, Value interface{}
}

MapItem is an item in a MapSlice.

type MapSlice

type MapSlice []MapItem

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

type Marshaler

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

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.

type TypeError

type TypeError struct {
	Errors []string
}

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.

func (*TypeError) Error

func (e *TypeError) Error() string

type Unmarshaler

type Unmarshaler interface {
	UnmarshalYAML(unmarshal func(interface{}) error) 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. Generally, the idea is to call the method to unmarshal into a value of the correct type, then use this unmarshalled value wherever you need to.

For example:

type T struct {
    values map[string]int
    sum    int
}

func (t *T) UnmarshalYAML(unmarshaler func(interface{}) error) error {

    if err := unmarshaler(t.values); err != nil {
        return err
    }

    for _, value := range t.values {
        t.sum += value
    }

    return nil
}

var t T
yaml.Unmarshal([]byte("T:\n  a: 1\n  b: 2\n  c:3"), &t)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL