Merge two mapping hierarchies from YAML files, preserving all keys
In this article, php editor Xigua will introduce how to merge two mapping hierarchies from YAML files and preserve all keys. The process is very simple and only requires the use of appropriate functions and methods. By merging two mapping hierarchies, we can combine their keys and values to create a larger, more comprehensive mapping hierarchy. Whether you are working with configuration files or data processing, merging mapping hierarchies is a very useful technique. Next, we will walk you through the process step by step so that you can easily master this technique.
Question content
I am working on a solution involving nested keys in a yaml file. The software will read the files passed in the parameters and load them in the order in which keys are updated/added.
I have 2 yaml files and I want to merge them without losing any keys. I want to stack all profiles to generate a single map without removing any keys.
So I have yaml 1
env: test1 template: app: database: name: oracle
yaml2
env: test2 template: app: database: version : 12
The result I want is (the order is yaml1 - yaml2)
env: test2 template: app: database: name: oracle version: 12
I tried copying using a map but since the keys have the same name I ended up with
env: test2 template: app: database: version: 12
I am using
gopkg.in/yaml.v3 for reading yaml provides me with the map[string] interface{}
and map using copy
package main import ( "fmt" "log" "maps" "os" "path/filepath" "gopkg.in/yaml.v3" ) type configuration struct { c m fl []string } type m = map[string]interface{} func (c *configuration) Update(nc m) { if c.c == nil { c.c = nc } else { maps.Copy(c.c, nc) } } func (c configuration) Print() { d, err := yaml.Marshal(&c.c) if err != nil { log.Fatalf("error: %v", err) } fmt.Printf("---:\n%s\n\n", string(d)) } func (c configuration) ParseDir(path string) { } func (c *configuration) LoadFromFile(filename string) { // YAML string stored in a variable yf, yfErr := os.ReadFile(filename) if yfErr != nil { log.Fatal("Error reading the file ", yfErr) } // Map to store the parsed YAML data var data m // Unmarshal the YAML string into the data map err := yaml.Unmarshal(yf, &data) if err != nil { log.Fatal(err) } c.Update(data) } func listFiles(path string) []string { var returnLf []string err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if info.Mode().IsRegular() { returnLf = append(returnLf, path) } return nil }) if err != nil { log.Println(err) } return returnLf }
Workaround
Suppose you want to merge YAML maps with "template" as the key from two YAML documents, a fairly simple implementation would look like this:
package main import ( "fmt" "gopkg.in/yaml.v3" ) const data1 = `--- env: test1 template: app: database: name: oracle foo: whatever ` const data2 = `--- env: test2 template: app: some_stuff: [1, 2, 3, 4] database: version : 12 foo: 42 ` type T struct { Env string `yaml:"env"` Tmpl map[string]any `yaml:"template"` } func mergeMapsRecursively(dst, src map[string]any) map[string]any { res := make(map[string]any) for dstKey, dstVal := range dst { srcVal, exists := src[dstKey] if !exists { res[dstKey] = dstVal continue } dstValMap, dstValIsMap := dstVal.(map[string]any) srcValMap, srcValIsMap := srcVal.(map[string]any) if dstValIsMap && srcValIsMap { res[dstKey] = mergeMapsRecursively(dstValMap, srcValMap) } else { res[dstKey] = srcVal } } for srcKey, srcVal := range src { if _, exists := dst[srcKey]; !exists { res[srcKey] = srcVal } } return res } func main() { var a, b T if err := yaml.Unmarshal([]byte(data1), &a); err != nil { panic(err) } if err := yaml.Unmarshal([]byte(data2), &b); err != nil { panic(err) } fmt.Printf("%#v\n%#v\n%#v\n", a.Tmpl, b.Tmpl, mergeMapsRecursively(a.Tmpl, b.Tmpl)) }
mergeMapsRecursively
Function recursively merges fields that exist in two maps (if they are both maps), or replaces the value in dst
with src
value in , otherwise — just like maps.Copy
does.
If this isn't exactly what you asked for, I hope my example will get you on the right track anyway.
The above is the detailed content of Merge two mapping hierarchies from YAML files, preserving all keys. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.
