Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple usage example of the public API #2021

Open
Skarlso opened this issue Apr 25, 2024 · 0 comments
Open

Simple usage example of the public API #2021

Skarlso opened this issue Apr 25, 2024 · 0 comments

Comments

@Skarlso
Copy link

Skarlso commented Apr 25, 2024

Hello.

I just would like to provide a basic usage example of the API that yq offers. I don't know if the API is stable, but currently, this works:

package main

import (
	"bytes"
	"fmt"
	"log"
	"strings"

	"github.com/mikefarah/yq/v4/pkg/yqlib"
)

func main() {
	dec := yqlib.NewYamlDecoder(yqlib.NewDefaultYamlPreferences())
	if err := dec.Init(strings.NewReader(`
a:
  b: val
`)); err != nil {
		log.Fatal(err)
	}

	node, err := dec.Decode()
	if err != nil {
		log.Fatal(err)
	}

	result, _ := yqlib.NewAllAtOnceEvaluator().EvaluateNodes(`.a.b = "nope
nope2
"`, node)
	fmt.Println(result)

	encoder := yqlib.NewYamlEncoder(yqlib.NewDefaultYamlPreferences())
	out := new(bytes.Buffer)
	printer := yqlib.NewPrinter(encoder, yqlib.NewSinglePrinterWriter(out))
	if err := printer.PrintResults(result); err != nil {
		log.Fatal(err)
	}
	fmt.Println(out.String())
}

I'm leaving this for anyone looking for examples for using the library instead of the CLI. I haven't found any documentation describing that, so most of the knowledge came from looking at the tests and the CLI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant