I have a fairly simple YAML document to parse into a (preferably) map in Go.
YAML doc:
---
A: Logon
'0': Heartbeat
'1': Test Request
'2': Resend Request
'3': Reject
'4': Sequence Reset
'5': Logout
'8': Execution Report
S: Quote
AE: Trade Capture Report
B: News
h: Trading Session Status
f: Security Status
I'm trying to marshal it with
type TranslationVal struct {
Map map[string]string
}
translationVal := TranslationVal{}
err := yaml.Unmarshal([]byte(val), &translationVal)
However I'm getting:
2017/08/22 20:33:23 yaml: unmarshal errors: line 1: cannot unmarshal !!str `A` into main.TranslationVal
The issue is caused by you wrapping the map in an object, the YAML has no such nesting.
map := map[string]string{}
err := yaml.Unmarshal([]byte(val), &map)
You can actually just unmarshal directly into the map itself
EDIT: hard to tell with your formatting but if those integer keys are nested under A
then you will need a different structure as well, it would actually be a map[string]map[string]string
-- however that is rather ugly so I would recommend moving to a different paradigm at that point... You could either use a map[string]interface{}
which wouldn't care what types go into the map and then you could deal with it later or you could define the object more statically, using actually keys such a A
in a struct to denote where each item goes, if that were the case you'd have an object like the following;
type TranslationVal struct {
A map[string]string
B string
C string
// and so on
F string `yaml:f` // necessary because f would be unexported
}
I actually tried to parse a value that wasn't YAML at all, doh!!