profile
viewpoint

Ask questionsunmarshal with comments provide wrong structure

This is the version

module mta_parse

go 1.12

require gopkg.in/yaml.v3 v3.0.0-20190502103701-55513cacd4ae

and run the following code which includes valid yaml

package main

import (
	"fmt"
	"log"

	"gopkg.in/yaml.v3"
)

var (
	sourceYaml = `version: 1
type: verbose
kind : bfr

# my list of applications
applications:

#  First app
  - name: app1
    kind: nodejs
    path: app1
    exec:
      platforms: k8s
      builder: test
`
)

func main() {
	t := yaml.Node{}

	err := yaml.Unmarshal([]byte(sourceYaml), &t)
	if err != nil {
		log.Fatalf("error: %v", err)
	}

	b, err := yaml.Marshal(&t)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(b))
}

The output is

version: 1
type: verbose
kind: bfr


# my list of applications
applications:
  - #  First app
    name: app1
    kind: nodejs
    path: app1
    exec:
        platforms: k8s
        builder: test


Process finished with exit code 0

please see that the comment is starting the array and not the name property which should start the array .

expected yaml

 #  First app
 -  name: app1
    kind: nodejs
    path: app1
    exec:
        platforms: k8s
        builder: test

if I remove the comment (first app) it looks ok, but with the comment change the yaml to invalid yaml, I think the comment and the state of the yaml is one of the killer feature in V3

go-yaml/yaml

Answer questions niemeyer

The description above states it's invalid yaml. That looks and parses as valid yaml representing the same data that was unmarshalled.

We also currently do not attempt to preserve 100% of the formatting of the yaml parsed. The intent is to produce a format that most people would find pleasant by default. For example, in your input the comment is indented at a different column than the content it's documenting. At least to my taste that feels awkward.

useful!
source:https://uonfu.com/
Github User Rank List