goccy / go-yaml

YAML support for the Go language

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Marshaling With a LineComment Results in Broken YAML when the Value of a Key is an Empty List

michohl opened this issue · comments

Describe the bug
When using the yaml.MarshalWithOptions function combined with the yaml.WithComment option if there is an empty array on the same line as the key this will result in the value being written in the comment instead of as a value.

To Reproduce

The following snippet can be used in Go Playground (I would provide a link but it was failing to generate one for me):

package main

import (
	"fmt"

	"github.com/goccy/go-yaml"
)

var input []byte = []byte(`
type: default
description: test data
problem: []
`)

func main() {
	var f map[string]interface{}

	var err error
	if err = yaml.Unmarshal(input, &f); err != nil {
		panic(err)
	}

	var out []byte
	out, err = yaml.MarshalWithOptions(f, yaml.WithComment(
		yaml.CommentMap{
			"$.description": []*yaml.Comment{yaml.LineComment("This line has no problems writing the comment")},
			"$.problem":     []*yaml.Comment{yaml.LineComment("The problem is on this line of output")},
		},
	))

	fmt.Println(string(out))
}

Expected behavior
I would expect valid YAML to be written out and the value of problem would come before the comment character.

e.g.:

description: test data #This line has no problems writing the comment
problem: [] #The problem is on this line of output
type: default

Screenshots
This is the output I'm receiving when using the provided snippet:

description: test data #This line has no problems writing the comment
problem #The problem is on this line of output: []
type: default

Version Variables

  • Go version: 1.21.0
  • go-yaml's Version: v1.11.2

Additional context

If I switch from MarshalWithOptions -> Marshal and forgo the comments then the output is valid YAML. I have not done any testing with other option types.