Skip to content

Simple usage example of the public API #2021

Open

Description

@Skarlso

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.

Activity

  1. jaronnie commented on Jul 1, 2024

    @jaronnie

    how to disable log

  2. jaronnie commented on Jul 1, 2024

    @jaronnie

    image

  3. Skarlso commented on Jul 1, 2024

    @Skarlso
    Author

    Like this:

    package controllers
    
    import (
    	glog "gopkg.in/op/go-logging.v1"
    )
    
    // In production main func will take care of setting the log yq-lib log level.
    // In test we count on this to set the default log level for all tests.
    // We do this because yqlib log is very chatty even if it is sometimes very useful.
    // Of course in an individual test one could change the level and reset to the default
    // via a defer call.
    func init() {
    	glog.SetLevel(glog.WARNING, "yq-lib")
    }
  4. jaronnie commented on Jul 2, 2024

    @jaronnie

    Thanks

  5. rwxrob commented on Oct 12, 2024

    @rwxrob

    OMG! Thank you for this. Using EvaluateNodes was the secret sauce I needed to make real use of this.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions