Go:如何在 yaml 中保留根缩进?
Go: How Do I Preserve Root Indentation in yaml?
我在使用 go 和 yaml.v3
重新编码 YAML 文件时遇到问题。
基本上我有一个 YAML 文件,其根缩进为 6(根缩进 6 个空格)。
我需要读取此文件,然后操作一些值并重写文件,但是在将 YAML 结构重写为文件时,我丢失了这个缩进。
关于如何实现这一目标的任何想法?否则我可能会将该文件作为文本文件重新读取并添加缩进。
下面是我正在使用的代码。
YAML 文件摘录:
doc:
a: 'default'
b: 42
c: 3
structure: 'flat'
use_timezone: ''
kafka_nodes: 3
正在解析 YAML 文件并写回文件
var ymlConfig yaml.Node
err = yaml.Unmarshal([]byte(pullConfig()), &ymlConfig)
//code ommited for brievity (some value verification and modification)
file, err := os.OpenFile("config.yml", os.O_WRONLY, os.ModeAppend)
if err != nil {
panic(err)
}
defer file.Close()
d := yaml.NewEncoder(file)
d.SetIndent(4)// tried changing the indent but it does not change the root
defer d.Close()
if err := d.Encode(&ymlConfig); err != nil {
panic(err)
}
重新编码的结果
doc:
a: 'default'
b: 42
c: 3
structure: 'flat'
use_timezone: ''
kafka_nodes: 3
你可以做这么简单的事情。
package main
import (
"bytes"
"fmt"
"gopkg.in/yaml.v3"
)
func addRootIndent(b []byte, n int) []byte {
prefix := append([]byte("\n"), bytes.Repeat([]byte(" "), n)...)
b = append(prefix[1:], b...) // Indent first line
return bytes.ReplaceAll(b, []byte("\n"), prefix)
}
func main() {
t := struct {
Doc map[string]interface{}
} {
Doc: map[string]interface{}{
"a": "The meaning is...",
"b": 42,
},
}
b, _ := yaml.Marshal(t)
b = addRootIndent(b, 6)
fmt.Println(string(b))
}
要更改 yaml 文档中的缩进,请使用
func (e *Encoder) SetIndent(spaces int)
我在使用 go 和 yaml.v3
重新编码 YAML 文件时遇到问题。
基本上我有一个 YAML 文件,其根缩进为 6(根缩进 6 个空格)。
我需要读取此文件,然后操作一些值并重写文件,但是在将 YAML 结构重写为文件时,我丢失了这个缩进。 关于如何实现这一目标的任何想法?否则我可能会将该文件作为文本文件重新读取并添加缩进。
下面是我正在使用的代码。
YAML 文件摘录:
doc:
a: 'default'
b: 42
c: 3
structure: 'flat'
use_timezone: ''
kafka_nodes: 3
正在解析 YAML 文件并写回文件
var ymlConfig yaml.Node
err = yaml.Unmarshal([]byte(pullConfig()), &ymlConfig)
//code ommited for brievity (some value verification and modification)
file, err := os.OpenFile("config.yml", os.O_WRONLY, os.ModeAppend)
if err != nil {
panic(err)
}
defer file.Close()
d := yaml.NewEncoder(file)
d.SetIndent(4)// tried changing the indent but it does not change the root
defer d.Close()
if err := d.Encode(&ymlConfig); err != nil {
panic(err)
}
重新编码的结果
doc:
a: 'default'
b: 42
c: 3
structure: 'flat'
use_timezone: ''
kafka_nodes: 3
你可以做这么简单的事情。
package main
import (
"bytes"
"fmt"
"gopkg.in/yaml.v3"
)
func addRootIndent(b []byte, n int) []byte {
prefix := append([]byte("\n"), bytes.Repeat([]byte(" "), n)...)
b = append(prefix[1:], b...) // Indent first line
return bytes.ReplaceAll(b, []byte("\n"), prefix)
}
func main() {
t := struct {
Doc map[string]interface{}
} {
Doc: map[string]interface{}{
"a": "The meaning is...",
"b": 42,
},
}
b, _ := yaml.Marshal(t)
b = addRootIndent(b, 6)
fmt.Println(string(b))
}
要更改 yaml 文档中的缩进,请使用
func (e *Encoder) SetIndent(spaces int)