Go-处理-YAML

pkg.go.dev 中 yaml 文档
参考

使用 gopkg.in/yaml.v3 模块.

安装

1
go get gopkg.in/yaml.v3

使用

主要是一些函数接口的使用.

Marshal

Marshal 意为 “序列化”, 表示将数据对象转换为特定格式的过程.

在这里, yaml.Marshal() 将 Go 的数据结构转化为 YAML 格式.

函数签名为:

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

注意, interface{} 的意思是空接口类型, 即可以接受任意类型的值.

对于 structure 的 field tag, 有特殊格式为:

1
`(...) yaml:"[<key>][,<flag1>[,<flag2>]]" (...)`

flag 可以是:

  • omitempty, 非空
  • flow
  • inline
    (flag 决定 field 在一些场景下的 key 的取舍)

示例:

1
2
3
4
5
6
type T struct {
F int `yaml:"a,omitempty"`
B int
}
yaml.Marshal(&T{B: 2})
yaml.Marshal(&T{F: 1}}

Unmarshal

将序列化的数据转换为原始的数据对象.

函数签名为:

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

示例:

1
2
3
4
5
6
type T struct {
F int `yaml:"a,omitempty"`
B int
}
var t T
yaml.Unmarshal([]byte("a: 1\nb: 2"), &t)

实例

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"fmt"
"gopkg.in/yaml.v3"
"log"
)

type Person struct {
Name string `yaml:"name"`
Age int `yaml:"age"`
}

func main() {
var p Person
data := []byte(`
name: John Doe
age: 30
`)

err := yaml.Unmarshal(data, &p)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t:\n%v\n\n", p)
}

2

YAML 文件内容:

1
2
3
4
5
6
# output.yaml

person:
name: John Doe
age: 30
email: john.doe@example.com

读入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Person struct represents the person key in YAML.
type Person struct {
Name string `yaml:"name"`
Age int `yaml:"age"`
Email string `yaml:"email"`
}

import (
"fmt"
"gopkg.in/yaml.v3"
"os"
)

func main() {
// read the output.yaml file
data, err := os.ReadFile("output.yaml")

if err != nil {
panic(err)
}

// create a person struct and deserialize the data into that struct
var person Person

if err := yaml.Unmarshal(data, &person); err != nil {
panic(err)
}

// print the fields to the console
fmt.Printf("Name: %s\n", person.Name)
fmt.Printf("Age: %d\n", person.Age)
fmt.Printf("Email: %s\n", person.Email)
}

写入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func main() {
// Create an instance of the Person struct with sample data
person := Person{
Name: "John Doe",
Age: 30,
Email: "john.doe@example.com",
}

// Serialize the person struct into YAML format
data, err := yaml.Marshal(&person)

if err != nil {
panic(err)
}

// Write the serialized YAML data to a file named "output.yaml"
err = os.WriteFile("output.yaml", data, 0644)

if err != nil {
panic(err)
}

fmt.Println("Data written to output.yaml")
}

3

使用 map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package main

import (
"fmt"
"gopkg.in/yaml.v3"
)

func main() {
// Data for marshaling
data := map[string]interface{}{
"name": "John Doe",
"age": 30,
"email": "johndoe@example.com",
}

// Marshaling the data into YAML
yamlData, err := yaml.Marshal(data)

if err != nil {
fmt.Println("Error during marshaling:", err)
return
}

fmt.Println("Marshaled YAML data:")
fmt.Println(string(yamlData))

// Unmarshalling the YAML data into a map
var unmarshalledData map[string]interface{}
err = yaml.Unmarshal(yamlData, &unmarshalledData)

if err != nil {
fmt.Println("Error during unmarshalling:", err)
return
}

fmt.Println("\nUnmarshalled data:")
fmt.Println(unmarshalledData)
}

Go-处理-YAML
http://example.com/2024/01/20/Go-处理-YAML/
作者
Jie
发布于
2024年1月20日
许可协议