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

How can I merge two yaml files using yq library ? #1967

Open
mikefarah opened this issue Mar 7, 2024 Discussed in #1966 · 1 comment
Open

How can I merge two yaml files using yq library ? #1967

mikefarah opened this issue Mar 7, 2024 Discussed in #1966 · 1 comment

Comments

@mikefarah
Copy link
Owner

Discussed in #1966

Originally posted by GeorgeDuckman March 7, 2024
Hello,

I am attempting to use yq as a library in my Golang application. I want to merge two yaml contents that are contained in two different string variables.

I am aware that the yq command can be used to merge two YAML files :

yq -n 'load("file1.yaml") * load("file2.yaml")'

To use yqlib, I am using the StringEvaluator which only takes one input. I am concatenating my two variables into one as follows:

---
a: Hello
---
a: Goodbye

And I want the result to be :

---
a: Goodbye

Is there a way to do this ? I would prefer not to create temporary files if possible :)
I've also tried merging by select but it returns nothing.

Here is my minimal code sample if you want to try yourself :

package main

import (
	"fmt"
	"log"

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

func main() {
	yamlA := "---\n" +
		"a: Hello"

	yamlB := "---\n" +
		"a: Goodbye"

	yaml := yamlA + "\n" + yamlB

	se := yqlib.NewStringEvaluator()
	expression := "select(document_index == 0) * select(document_index == 1)"
	strung, err := se.Evaluate(expression, yaml, yqlib.NewYamlEncoder(2, true, yqlib.YamlPreferences{}), yqlib.NewGoccyYAMLDecoder())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(strung)
}

Thank you in advance !

@mikefarah
Copy link
Owner Author

There actually isn't a great way to do that at the moment, the Evaluate function runs through the documents inside the string one by one as a stream. I've added a new "EvaluateAll" function to StringEvaluator that you can use in the next release.

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

No branches or pull requests

1 participant