goyaml: case sensitive keys

411 views
Skip to first unread message

davie...@gmail.com

unread,
Sep 25, 2013, 7:33:17 AM9/25/13
to golan...@googlegroups.com
Hi,

I'm using goyaml (https://wiki.ubuntu.com/goyaml). I have a newbie question about unmarhall and the case of keys.

I get that to use Unmarshal() properly, the fields have to be public (i.e. starting with a capital letter). Therefore, I expect "test" in a YAML file to end up in field "Test". This works - as expected. However, if I have a field with a capital letter in the YAML file, and the struct also has a capital (i.e. Test  in the struct, and Test: x in the yaml file) I would also expect this to work - but it does not. 

I strongly suspect this isnt a bug but my misunderstanding, can anyone point me in the right direction? Example code below - this does not work, but if you change the Test to 'test' in the string 

Thanks!

  1 package main
  2
  3 import "fmt"
  4 import "launchpad.net/goyaml"
  5
  6 type A struct {
  7   Test  string
  8 }
  9
 10 func main() {
 11     testcases := []string{ "- Test: test", "- test: test" }
 12     for _,testcase := range testcases {
 13         a :=   []byte(testcase)
 14
 15         i := []A{}
 16         goyaml.Unmarshal(a, &i)
 17
 18         j := i[0]
 19         fmt.Printf ("Value of test field for test case %s: %s\n", testcase, j.Test)
 20     }
 21 }

This outputs:

[adavies@ljoit-adl1 halServerJobController (master)]$ go run test.go
Value of test field for test case - Test: test:
Value of test field for test case - test: test: test

Gustavo Niemeyer

unread,
Sep 25, 2013, 10:18:04 AM9/25/13
to davie...@gmail.com, golan...@googlegroups.com
On Wed, Sep 25, 2013 at 8:33 AM, <davie...@gmail.com> wrote:
> I'm using goyaml (https://wiki.ubuntu.com/goyaml). I have a newbie question
> about unmarhall and the case of keys.

It defaults to the lowercased field name, because that's by far the
most common convention on yaml files, but you can tweak that behavior
by using the field tag as usual. The documentation describes it [1]:

"""
In the case of struct values, only exported fields will be serialized.
The lowercased field name is used as the key for each exported field,
but this behavior may be changed using the respective field tag. The
tag may also contain flags to tweak the marshalling behavior for the
field. Conflicting names result in a runtime error. The tag format
accepted is: (...)
"""

[1] http://godoc.org/launchpad.net/goyaml#Marshal


gustavo @ http://niemeyer.net
Reply all
Reply to author
Forward
0 new messages