New Gopher here! I am working with a rest API in go, and I am now working on parsing out my first return JSON and seem to be having a bit of trouble.
First the raw return from the API call nets me this:
spew.Dump(body)
(string) (len=205) "{\"return\": {
\"apiMajorVersion\": 3,
\"apiMinorVersion\": 0,
\"esmMajorVersion\": 9,
\"esmMinorVersion\": 5,
\"esmPatch\": \"MR7\",
\"esmRevision\": 0,
\"esmVersionString\": \"9.5.0 20150908\"
}}"
With all the backslashes and newlines embedded in the string. If I print it
fmt.Println(body)
{"return": {
"apiMajorVersion": 3,
"apiMinorVersion": 0,
"esmMajorVersion": 9,
"esmMinorVersion": 5,
"esmPatch": "XX7",
"esmRevision": 0,
"esmVersionString": "9.5.0 20150908"
}}
Then I get valid json.
If I try and unmarshal it to the struct I don't get the values in the struct properly.
type ESMVersionStruct struct {
APIMajorVersion int8 `json:"return>apiMajorVersion"`
APIMinorVersion int8 `json:"apiMinorVersion"`
ESMMajorVersion int8 `json:"esmMajorVersion"`
ESMMinorVersion int8 `json:"esmMinorVersion"`
ESMPatch string `json:"esmPatch"`
ESMRevision int8 `json:"esmRevision"`
ESMVersionString string `json:"esmVersionString"`
}
I have tried both specifying the object in the return and not.
jsonData := []byte(body)
var ESMVersion ESMVersionStruct
json.Unmarshal(jsonData, &ESMVersion)
fmt.Println(ESMVersion.APIMajorVersion)
fmt.Print(ESMVersion.APIMinorVersion)
Both of the last two return the null value.
Thanks in advance for any help with this one!
Your type should be:
type ESMVersionStruct struct {
Return struct {
APIMajorVersion int8 `json:"apiMajorVersion"`
APIMinorVersion int8 `json:"apiMinorVersion"`
ESMMajorVersion int8 `json:"esmMajorVersion"`
ESMMinorVersion int8 `json:"esmMinorVersion"`
ESMPatch string `json:"esmPatch"`
ESMRevision int8 `json:"esmRevision"`
ESMVersionString string `json:"esmVersionString"`
} `json:"return"`
}
That is, your struct embedded in another Return
struct.