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

Empty maps are marshal'd as JSON #708

Closed
TomWright opened this issue Mar 5, 2021 · 2 comments
Closed

Empty maps are marshal'd as JSON #708

TomWright opened this issue Mar 5, 2021 · 2 comments

Comments

@TomWright
Copy link

Hey,

I've noticed that empty maps are marshal'd as JSON documents, for example:

package main

import (
	"bytes"
	"fmt"
	"gopkg.in/yaml.v2"
)

func main() {
	// {}
	encode(map[string]interface{}{})

	// ""
	encode("")

	// a: b
	encode(map[string]interface{}{
		"a": "b",
	})
}

func encode(val interface{}) {
	buffer := new(bytes.Buffer)
	encoder := yaml.NewEncoder(buffer)
	defer encoder.Close()
	if err := encoder.Encode(val); err != nil {
		panic(err)
	}
	fmt.Println(string(buffer.Bytes()))
}

Is this expected?

Is there any way to just have an empty YAML document (a blank string?) output instead?

@niemeyer
Copy link
Contributor

niemeyer commented Mar 5, 2021

A blank string represents the null YAML value. An empty map is represented with the {} YAML mapping in flow style. These are different YAML values, so we can't exchange one by the other.

@niemeyer niemeyer closed this as completed Mar 5, 2021
@TomWright
Copy link
Author

Thanks for that feedback - you learn something new every day!

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

2 participants