How to retrieve/print the final YAML string after YAML files are loaded and merged?
brightzheng100 opened this issue · comments
This is NOT a bug, instead, it's an ask.
It's common to load some YAML files and merge them to generate a so-called "effective" YAML and then print it out.
But I don't know how to print it out as a valid YAML string.
Is there an API to do something like k.ToString()
to print out the Koanf object as a YAML string after files are merged?
You can maybe do something like this?
package main
import (
"log"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/rawbytes"
"github.com/knadh/koanf/v2"
)
var k = koanf.New(".")
func main() {
log.Println(k.Load(rawbytes.Provider([]byte(`key1: val
name1: test
number1: 2`)), yaml.Parser()))
k.Print()
log.Println(k.Load(rawbytes.Provider([]byte(`key2: val
name2: test
number2: 2`)), yaml.Parser()))
k.Print()
b, _ := k.Marshal(yaml.Parser())
log.Println("result\n", string(b))
}
2023/11/17 13:49:04 <nil>
key1 -> val
name1 -> test
number1 -> 2
2023/11/17 13:49:04 <nil>
key1 -> val
key2 -> val
name1 -> test
name2 -> test
number1 -> 2
number2 -> 2
2023/11/17 13:49:04 result
key1: val
key2: val
name1: test
name2: test
number1: 2
number2: 2
Cool, that works for me. Thank you @rhnvrm!
Not sure whether it's a good idea to have a new API like:
// ToString takes a Parser implementation and generate the config map into string,
// for example, to TOML or JSON string.
func (ko *Koanf) ToString(p Parser) (string, error) {
bytes, err := p.Marshal(ko.Raw())
if err != nil {
return "", err
}
return string(bytes), nil
}
I think the current API should suffice as the ToString method would just be a utility func that converts the output to string.
https://github.com/knadh/koanf#unmarshalling-and-marshalling
k.Sprint()
returns the human readable form.
You can also marshal to YAML, TOML etc. See https://github.com/knadh/koanf#unmarshalling-and-marshalling
I think it's fine for me now as long as I know how to generate the YAML string from the object.
And maybe this thread may help others who are curious.