Craig
Craig

Reputation: 151

go string handling and JSON

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\": {\n    \"apiMajorVersion\": 3,\n    \"apiMinorVersion\": 0,\n    \"esmMajorVersion\": 9,\n    \"esmMinorVersion\": 5,\n    \"esmPatch\": \"MR7\",\n    \"esmRevision\": 0,\n    \"esmVersionString\": \"9.5.0 20150908\"\n}}"

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!

Upvotes: 1

Views: 75

Answers (1)

Simon
Simon

Reputation: 32923

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.

Upvotes: 2

Related Questions