go-yaml / yaml

YAML support for the Go language.
Other
6.77k stars 1.03k forks source link

Objects should be decoded into map[string]interface{} instead of map[interface{}]interface{} #824

Closed bluebrown closed 2 years ago

bluebrown commented 2 years ago

The standard lib JSON package decodes objects into map[string]interface{}. That is useful when trying to marshal the result again.

This YAML package decodes into map[interface{}]interface{} which is causing errors when trying to marshal the result.

I actually don't see any reason why map[interface{}]interface{} is required. Object keys in, YAML and JSON, can only be strings, there is no other option. At least as far as I can tell.

https://play.golang.com/p/KwXpFr8KC08

Example Code: ```golang package main import ( "encoding/json" "fmt" "io" "strings" "gopkg.in/yaml.v2" ) func main() { fmt.Printf("JSON\n-------\n") test(decodeJson) fmt.Printf("\nYAML\n-------\n") test(decodeYaml) } func test(decode func(s string) interface{}) { v := decode(`{"foo": "bar"}`) fmt.Printf("%T\n", v) b, err := json.MarshalIndent(v, "", " ") if err != nil { panic(err) } println(string(b)) } func decodeYaml(s string) interface{} { dec := yaml.NewDecoder(strings.NewReader(s)) var v interface{} for { if err := dec.Decode(&v); err == io.EOF { break } else if err != nil { panic(err) } } return v } func decodeJson(s string) interface{} { dec := json.NewDecoder(strings.NewReader(s)) var v interface{} for { if err := dec.Decode(&v); err == io.EOF { break } else if err != nil { panic(err) } } return v } ``` Output: ``` JSON ------- map[string]interface {} { "foo": "bar" } YAML ------- map[interface {}]interface {} panic: json: unsupported type: map[interface {}]interface {} goroutine 1 [running]: main.test(0x542a00) /home/blue/projects/own/cmdpipe/main.go:24 +0x106 main.main() /home/blue/projects/own/cmdpipe/main.go:16 +0x7b exit status 2 ```
bluebrown commented 2 years ago

sorry, somehow this issue was submitted 3 times